我有一个关于斯威夫特的仿制药的问题。为什么不可能?
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<>()
在Java中,是否有一个等价形式?
最佳答案
这与swift中的泛型协方差有关。基本上,GenerifiedClass<SuperType>
不是GenerifiedClass<TypeA>
的超类,而是一个兄弟类,这就是为什么在使用多态性时不能使用它的原因。
要回答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]