Extend existing protocols to implement another protocol with default implements

后端 未结 2 828
陌清茗
陌清茗 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-29 23:51

    You can make A inherits from B:

    protocol A: B { var a: String { get } }
    protocol B    { var b: String { get } }
    
    // Default implementation of property b
    extension A {
        var b: String { get { return "PropertyB" } }
    }
    
    
    class MyClass: A {
        var a: String { get { return "PropertyA" } }
    
        func printA(obj: A) {
            print(obj.a)
            printB(obj)
        }
    
        func printB(obj: B) {
            print(obj.b)
        }
    }
    
    let obj = MyClass()
    obj.printA(obj)
    

    Since A inherits from B, every property in B is available in A.

提交回复
热议问题