我有一个关于 Swift 泛型的问题。为什么这不可能?
class GenerifiedClass<T> {
func doSomething(thing: T) {
print("doing something with \(thing)")
}
}
class SuperType {}
class TypeA: SuperType {}
class TypeB: SuperType {}
class TypeC: SuperType {}
let a = GenerifiedClass<TypeA>()
let b = GenerifiedClass<TypeB>()
let c = GenerifiedClass<TypeC>()
let array: [GenerifiedClass<SuperType>] = [a, b, c] // compile error
澄清我的问题:为什么我不能将数组输入为 [GenerifiedClass<SuperType>]
?我有点知道为什么,因为例如在 Java 中这也是不可能的。但至少在 Java 中有解决这个问题的语法:
List<? extends SuperType> list = new ArrayList<>()
Swift 中是否有相当于 <? extends SuperType>
的内容在Java 中?
最佳答案
这与 Swift 中泛型的协方差有关。基本上GenerifiedClass<SuperType>
不是 GenerifiedClass<TypeA>
的父类(super class),但只是一个兄弟类,这就是为什么你不能在需要使用多态性的地方使用它。
回答extends
问题,是的,这在 Swift 中也是可能的:
class SuperType {}
class TypeA: SuperType {}
class TypeB: SuperType {}
class TypeC: SuperType {}
let a = TypeA()
let b = TypeB()
let c = TypeC()
let array: Array<SuperType> = [a, b, c]
,或
let array: [SuperType] = [a, b, c]
关于swift - 在数组中使用泛型父类(super class)型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34902912/