【发布时间】:2019-05-30 00:09:56
【问题描述】:
我试图弄清楚如何将用不同类型实例化的泛型作为抽象一起使用。例如,将它们放在一个数组中或将它们传递给一个函数。我知道这很棘手,因为对象在编译时需要一个具体的类。然而,在尝试使用作为具体类时,我偶然发现了下面的操场代码。即使类被实例化为Generic1<Any>,也能正确识别底层值属性的类型。所以我的谜团是这样的:即使type(of:g1) 是Generic1<Any>,type(of: g1.value) 怎么可能是Int?既然如此,为什么我不能将g1 转换为Generic1<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
--------------------
【问题讨论】: