繁体   English   中英

如何转换通用T以符合协议

[英]How to cast generic T to conform to protocol

我需要在类中强制转换通用类型以符合协议。 由于容器类必须序列化,因此无法使用约束。 那么,在我已经知道(我可以检查一下)它符合协议的情况下,如何在这种情况下将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

因为必须在编译时就知道泛型,所以不能只在运行时检查一致性(我很确定)。 我认为这更像您想要的:

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)
    }
}

较具体的初始化程序将在编译时选择。

我想你在找这个。

protocol ZNumeric {

}

extension Double: ZNumeric {

}

class GenericClass<T> {

}

class RestrictedGenericClass<T:ZNumeric> {

}

class Container<T> {
    required init?(value: T) {
    }
    convenience init?(_ value: T) {
        self.init(value: value)
        let a = GenericClass<T>()
        print(a)
    }
}
extension Container where T: ZNumeric {
    convenience init?(_ value: T) {
        self.init(value: value)
        let b = RestrictedGenericClass<T>() // Will not work obviously
        print(b)
    }
}

print("test Double")
let cDouble = Container(1.1) // if T.self is ZNumeric.Type is true
print("test String")
let cString = Container("") // if T.self is ZNumeric.Type is false

// test Double
// RestrictedGenericClass<Swift.Double>
// test String
// GenericClass<Swift.String>
  1. 使内部需要初始化
  2. 为T创建初始化器:AnyObject
  3. 为T创建初始化器:ZNumeric

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM