Calling protocol default implementation from regular method

前端 未结 6 1629
暖寄归人
暖寄归人 2020-11-30 19:16

I\'m wondering if it\'s possible to achieve such a thing.
I have a Playground like this:

protocol Foo {
    func testPrint()
}

extension Foo {
    func          


        
6条回答
  •  Happy的楠姐
    2020-11-30 20:02

    what do you think about such way of fixing this ?

    protocol Foo {
        func testPrint()
    }
    
    extension Foo {
        func testPrint() {
            defaultTestPrint()
        }
    
        func defaultTestPrint() {
            print("Protocol extension call")
        }
    }
    
    struct Bar: Foo {
        func testPrint() {
            // Calling self or super go call default implementation
            defaultTestPrint()
            print("Call from struct")
        }
    }
    
    
    let sth = Bar()
    sth.testPrint()
    

提交回复
热议问题