Extend existing protocols to implement another protocol with default implements

后端 未结 2 840
陌清茗
陌清茗 2020-12-29 23:15

Is it possible to add protocol compliance to a different protocol by way of an extension?

For instance we would like A to comply with B:

protocol A {         


        
2条回答
  •  悲&欢浪女
    2020-12-30 00:08

    When extending A, you could specify that the type also conforms to B:

    extension A where Self: B {
        var b : UIView {
            return self.a
        }
    }
    

    Then make your type conform to A and B, e.g.

    struct MyStruct : A, B {
        var a : UIView {
            return UIView()
        }
    }
    

    Due to the protocol extension, instances of MyStruct will be able to use a and b, even though only a was implemented in MyStruct:

    let obj = MyStruct()
    obj.a
    obj.b
    

提交回复
热议问题