如何投射通用T符合协议 [英] How to cast generic T to conform to protocol
本文介绍了如何投射通用T符合协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在类中转换泛型以符合协议。因为容器类必须被序列化,所以我不能使用约束。所以我怎么能在这种情况下将T转换为ZNumeric,当我已经知道(我可以检查,因为你看到),它符合协议?
//:Playground - 名词:人们可以玩的地方
导入UIKit
协议ZNumeric {
}
扩展名Double:ZNumeric {
}
class GenericClass< T> {
}
class RestrictedGenericClass< T:ZNumeric> {
}
class容器{
需要init?< T>(type:T.Type){
let a = GenericClass< T> ;()
print(a)
如果T.self为ZNumeric.Type {
print(is numeric)
// let b = RestrictedGenericClass< T>()//不会明显工作
//打印(b)
}
}
}
让cDouble =容器(类型: Double.self)//如果T.self是ZNumeric.Type是true
let cString = Container(type:String.self)//如果T.self是ZNumeric.Type是false
$因为必须在编译时知道泛型,所以你不能只在运行时检查,因为泛型必须在编译时被知道,遵守的时间(我很确定)。我认为这更像是你想要的:
class Container {
required init?< T>(type :T.Type){
let a = GenericClass< T>()
print(a)
}
需要init?< T:ZNumeric>(类型:T.Type){
let a = GenericClass< T>()
print(a)
print(is numeric)
let b = RestrictedGenericClass< T>()
print(b)
}
}
更具体的初始化程序将在编译时选择。
I need to cast the generic type in a class to conform to a protocol. I can not use constraints since the container class has to be serialized. So how could i cast in this case the T to ZNumeric when i allready know (i can check as you see) that it conforms to the protocol?
//: 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
解决方案 Because generics have to be known at compile-time, you cannot just check at run-time for conformance (I'm pretty sure). I think this is more like what you want:
class Container {
required init?<T>(type: T.Type) {
let a = GenericClass<T>()
print(a)
}
required init?<T : ZNumeric>(type: T.Type) {
let a = GenericClass<T>()
print(a)
print("is numeric")
let b = RestrictedGenericClass<T>()
print(b)
}
}
The more specific initialiser will be chosen at compile-time.
这篇关于如何投射通用T符合协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文