Swift泛型类型强制转换 [英] Swift generic type cast
问题描述
我有一个泛型类,我有一个泛型类型的数组。不,我想根据数组中的类进行一些操作。我有2个班级:人与家(无继承)。但是这段代码不起作用:
let allValues = [T]()
如果allValues [0]是Person {
let values =(allValues as [Person])
}
但是这不起作用,因为 T与'Person'不一样。我需要做什么?感谢您的帮助。
strong>:这种问题应该使用协议解决。然而,您可以使用此语法执行演员阵容:
让values = allValues as Any作为[Person]
现在我看到两个问题:
- 您的 IF 会因为您的数组 allValues 包含0
元素,并且您正在访问第一个元素(不存在)。 -
allValues可以在第一个元素处具有Person,在第二个位置还有
的东西。
示例
class LifeForm {}
p>
类Person:LifeForm {}
T等于LifeForm。
我认为以下版本更安全,因为您直接评估T类型。
class Things< T> {
func doSomething(){
let allValues = [T]()
//填充allValues ....
如果T.self是Person.Type {
println(Person of List)
让values = allValues as Any作为[Person]
}
}
}
重要提示:我提供此代码仅用于显示语法。我不喜欢这个abborach(再次,一个协议会更好),因为这个类包含特定于Person的逻辑。
理想情况 对 Person 应该一无所知,因为事物是泛型类。
I have a generic class where I have an array of generic types. No I want to do some operations based on the class in the array. I have 2 classes: Person and House (no Inheritance). But this code doesn't work:
let allValues = [T]()
if allValues[0] is Person {
let values = (allValues as [Person])
}
But this doesn't work as T is not identical to 'Person'. What do I have to do? Thanks for any help.
I agree with Oliver Borchert and Airspeed Velocity: this kind of problem should be addressed using a protocol.
However you can perform the cast you asked about using this syntax:
let values = allValues as Any as [Person]
Now I see 2 problems:
- Your IF will crash because your array allValues contains 0 elements and you are accessing the first one (that does not exist).
allValues could have a Person at the first element and something else at the second position. This makes dangerous a cast after having evaluated only the first element.
Example
class LifeForm {}
class Person : LifeForm {}
With T equals to LifeForm.
I think the following version is safer because you are directly evaluating the type T.
class Things<T>{
func doSomething() {
let allValues = [T]()
// populate allValues....
if T.self is Person.Type {
println("List of Person")
let values = allValues as Any as [Person]
}
}
}
Important: I provided this code just to show the syntax. I don't like this abborach (again, a Protocol would be better) because the class Things contains logic specific to Person. Ideally Things should know nothing about Person because Things is a generic class.
这篇关于Swift泛型类型强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!