简体   繁体   English

Swift 在子协议中用具体类型替换关联类型

[英]Swift replace associated type with concrete type in sub-protocol

protocol A {
    associatedtype T
    var t: T { get }
}

protocol B: A where T == Int {}

var b: B? = nil     //  Protocol 'B' can only be used as a generic constraint
                    //  because it has Self or associated type requirements.
                    

Is there a way to create an extended protocol (B) that assigns a concrete type to the base protocol's (A's) associated type, and by doing so "removes" the associated type requirements, and becomes a protocol with no associated types, usable not only as a generic constraint?有没有办法创建一个扩展协议(B),将具体类型分配给基本协议(A)的关联类型,并通过这样做“删除”关联类型要求,并成为没有关联类型的协议,不可用仅作为通用约束?

No, it doesn't seem to work so the associated type always stays inside不,它似乎不起作用,所以关联的类型总是留在里面

protocol A {
    associatedtype T
    var t: T { get }
}

protocol B: A {
    override associatedtype T = Int
}

There are methods to overcome this, for example wrapped classes有一些方法可以克服这个问题,例如包装类

 class WrappedB: B {
    var t: Int
    
    init<S: B>(_ object: S) where S.T == Int {
        self.t = object.t
    }
}

var b: WrappedB = WrappedB(BB())

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

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