Calling protocol default implementation from regular method

前端 未结 6 1633
暖寄归人
暖寄归人 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条回答
  •  猫巷女王i
    2020-11-30 19:56

    I don't know if you are still looking for an answer to this, but the way to do it is to remove the function from the protocol definition, cast your object to Foo and then call the method on it:

    protocol Foo { 
        // func testPrint() <- comment this out or remove it
    }
    
    extension Foo {
        func testPrint() {
            print("Protocol extension call")
        }
    }
    
    struct Bar: Foo {
        func testPrint() {
            print("Call from struct")
            (self as Foo).testPrint() // <- cast to Foo and you'll get the  default
                                      //    function defined in the extension
        }
    }
    
    Bar().testPrint()
    
    // Output:    "Call from struct"
    //            "Protocol extension call"
    

    For some reason it only works if the function isn't declared as part of the protocol, but is defined in an extension to the protocol. Go figure. But it does work.

提交回复
热议问题