Calling protocol default implementation from regular method

前端 未结 6 1627
暖寄归人
暖寄归人 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条回答
  •  渐次进展
    2020-11-30 19:58

    Thanks for the post! If you put the function definition in the protocol then when the object is casted as the protocol it only sees the object's version of the function and since you are calling it inside itself you get the new address of Apple ...

    I did try a version like this:

    import UIKit
    protocol MyProc
    {
    }
    
    protocol MyFuncProc
    {
        func myFunc()
    }
    
    extension MyProc
    {
        func myFunc()
        {
            print("Extension Version")
        }
    }
    
    struct MyStruct: MyProc, MyFuncProc
    {
        func myFunc()
        {
            print("Structure Version")
            (self as MyProc).myFunc()
        }
    }
    
    (MyStruct() as MyFuncProc).myFunc()
    

    This gives an output of:

    Structure Version
    Extension Version
    

提交回复
热议问题