【发布时间】:2016-04-27 14:45:39
【问题描述】:
我需要在类中转换泛型类型以符合协议。我不能使用约束,因为容器类必须被序列化。那么在这种情况下,当我已经知道(我可以检查你所看到的)它符合协议时,我怎么能将 T 转换为 ZNumeric?
//: Playground - noun: a place where people can play
import UIKit
protocol ZNumeric {
}
extension Double: ZNumeric {
}
class GenericClass<T> {
}
class RestrictedGenericClass<T:ZNumeric> {
}
class Container {
required init?<T>(type: T.Type) {
let a = GenericClass<T>()
print(a)
if T.self is ZNumeric.Type {
print("is numeric")
//let b = RestrictedGenericClass<T>() // Will not work obviously
//print(b)
}
}
}
let cDouble = Container(type: Double.self) // if T.self is ZNumeric.Type is true
let cString = Container(type: String.self) // if T.self is ZNumeric.Type is false
【问题讨论】: