swift - 为什么其各自类型参数符合继承关系的泛型类型本身不符合类似关系?

标签 swift generics inheritance

在 Swift 中,当你有 SubType 时继承自一些 SuperType ,并且有一个GenericType<TypeParameter>可以接受其 TypeParameter任一类的实例( SubTypeSuperType ),为什么 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/

相关文章:

java - 转换为有界类型

Python:在派生类中隐藏基类的成员

ios - 如何在 “Framework Search Paths” 部分添加 RealmSwift.framework 的父路径?

swift - 在 Swift 4 中通过函数高级转换 UTF16View.Index

ios - 应用程序启动时出现 NSUnknownKeyException

Java 泛型绑定(bind)类型和类型参数

swift - macOS - 使用 `Process` telnet 到一个 IP 地址并传递命令

c# - 通用接口(interface)的嵌套契约

java - 绕过不良设计实践 : Java Multiple Inheritance

Java 对象使用 Jackson 将列表扩展为 Json