1
我需要在類中強制泛型以符合協議。因爲容器類必須被序列化,所以我不能使用約束。那麼我怎麼能在這種情況下將T轉換爲ZNumeric,當我已經知道(我可以檢查,因爲你看到),它符合協議?如何投射泛型T以符合協議
//: 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
啊,好,但在現實情況下,它是一個子類,然後整個想法打破:(這驅使我堅果http://stackoverflow.com/questions/33810702/possible-bug-i-can-create-generic-instance-ignoring-constraint – Alex