首页 > 解决方案 > 如何处理 GenericClass用于抽象

问题描述

我试图弄清楚如何将用不同类型实例化的泛型一起用作抽象。例如,将它们放在一个数组中或将它们传递给一个函数。我知道这很棘手,因为对象在编译时需要一个具体的类。然而,在尝试使用作为具体类时,我偶然发现了下面的操场代码。即使将类实例化为Generic1<Any>,也可以正确识别基础值属性的类型。所以我的谜团是这样的:即使是,怎么type(of: g1.value)可能呢?既然如此,为什么我不能投到?谢谢!Inttype(of:g1)Generic1<Any>g1Generic1<Int>

class Generic1<T> {
    var value: T
    init(_ value:T) {
        self.value = value
    }
}

func handleGeneric(_ g: Generic1<Any>) {
    print("--------------------")
    print(type(of:g))
    print(type(of:g.value))
    print(g.value)
    print("--------------------")
}


let g1 = Generic1<Any>(1)
let g2 = Generic1<Any>("hello")

handleGeneric(g1)
handleGeneric(g2)

输出

--------------------
Generic1<Any>
Int
1
--------------------
--------------------
Generic1<Any>
String
hello
--------------------

标签: iosswiftgenerics

解决方案


纵然是怎么type(of: g1.value)可能Inttype(of:g1)Generic1<Any>

type(of:)使用运行时类型信息(存储在实例使用的存在容器中Any)为您提供具体类型。我认为它永远不会返回超类、协议或除具体类型之外的任何东西。is 的具体类型,is的g1.value具体Int类型。g1Generic<Any>

为什么我不能g1投到Generic1<Int>

因为 Swift 的泛型不是协变的。也就是说,C<A>不是 的子类型C<B>,即使A是 的子类型B。见https://stackoverflow.com/a/30487474/3141234


推荐阅读