在 Swift 中,当你有 SubType
时继承自一些 SuperType
,并且有一个GenericType<TypeParameter>
可以接受其 TypeParameter
任一类的实例( SubType
或 SuperType
),为什么 GenericType<SubType>
的实例不能转换为GenericType<SuperType>
?
我听说这种行为存在于其他语言中,并且我希望它也存在于 Swift 中,所以我渴望在这里了解。
class SuperType {
}
class SubType: SuperType {
}
class GenericType<TypeParameter> {
func someGenericFunction() {
print(TypeParameter.self)
}
}
let instance = GenericType<SuperType>()
let subInstance = GenericType<SubType>()
instance.someGenericFunction() // prints "SuperType"
subInstance.someGenericFunction() // prints "SubType"
let array: [GenericType<SuperType>] = [instance, subInstance] // throws error: cannot convert value of type 'SomeGenericClass<SubType>' to expected element type 'SomeGenericClass<SuperType>'
最佳答案
恐怕没有简单的出路...... 如果您想将两个对象放入一个数组中,您可以引入一些描述所需行为的协议(protocol)
protocol MyProtocol {
func someGenericFunction()
}
然后确保您的 GenericType
符合它。
class GenericType<TypeParameter>: MyProtocol {
func someGenericFunction() {
print(TypeParameter.self)
}
}
那么..那么你可以这样将你的对象放入[MyProtocol]
数组中:
let instance = GenericType<SuperType>()
let subInstance = GenericType<SubType>()
instance.someGenericFunction() // prints "SuperType"
subInstance.someGenericFunction() // prints "SubType"
let array: [MyProtocol] = [instance, subInstance]
for object in array {
object.someGenericFunction() // prints "SuperType", "SubType"
}
关于swift - 为什么其各自类型参数符合继承关系的泛型类型本身不符合类似关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498740/