ios - 如何处理 GenericClass用于抽象
问题描述
我试图弄清楚如何将用不同类型实例化的泛型一起用作抽象。例如,将它们放在一个数组中或将它们传递给一个函数。我知道这很棘手,因为对象在编译时需要一个具体的类。然而,在尝试使用作为具体类时,我偶然发现了下面的操场代码。即使将类实例化为Generic1<Any>
,也可以正确识别基础值属性的类型。所以我的谜团是这样的:即使是,怎么type(of: g1.value)
可能呢?既然如此,为什么我不能投到?谢谢!Int
type(of:g1)
Generic1<Any>
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
--------------------
解决方案
纵然是怎么
type(of: g1.value)
可能Int
type(of:g1)
Generic1<Any>
type(of:)
使用运行时类型信息(存储在实例使用的存在容器中Any
)为您提供具体类型。我认为它永远不会返回超类、协议或除具体类型之外的任何东西。is 的具体类型,is的g1.value
具体Int
类型。g1
Generic<Any>
为什么我不能
g1
投到Generic1<Int>
因为 Swift 的泛型不是协变的。也就是说,C<A>
不是 的子类型C<B>
,即使A
是 的子类型B
。见https://stackoverflow.com/a/30487474/3141234
推荐阅读
- sql - 如何从同一个表中返回值?
- reactjs - 从数据库读取时不显示图像
- slice - 如何将 train_loss 和 valid_loss 与 epoch_loss 分开存储?
- visual-studio-2013 - 如何将自定义规则添加到“Resharper 的 StyleCop”?
- amazon-web-services - 自定义资源支持的 Lambda“CREATE_IN_PROGRESS”永远
- excel - 如何在每行使用单个数组公式时对当前列中的行求和()?
- python - 为什么 pd.MultiIndex.from_tuples 改变元组的顺序
- express - Angular: Proxy server truncates XHR response
- crystal-reports - 如何在英文水晶报告中显示单词中的数量
- c++ - arm aarch64 sizeof打包结构与32位不同