【问题标题】:Swift replace associated type with concrete type in sub-protocolSwift 用子协议中的具体类型替换关联类型
【发布时间】:2020-09-28 20:04:30
【问题描述】:
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.
                    

有没有办法创建扩展协议(B) 将具体类型分配给基本协议的(A) 关联类型,并通过这样做“删除”关联类型要求, 并成为没有关联类型的协议,不仅可用作通用约束?

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    不,它似乎不起作用,所以关联的类型总是留在里面

    protocol A {
        associatedtype T
        var t: T { get }
    }
    
    protocol B: A {
        override associatedtype T = Int
    }
    

    有一些方法可以克服这个问题,例如包装类

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2018-07-16
      • 2015-01-21
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多