Calling protocol default implementation from regular method

前端 未结 6 1632
暖寄归人
暖寄归人 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:59

    I have come up with a solution for this.

    
    protocol Foo {
        var defaultImplementation: DefaultImpl? { get }
        func testPrint()
    }
    
    extension Foo {
        // Add default implementation
        var defaultImplementation: DefaultImpl? {
            get {
                return nil
            }
        }
    }
    
    struct DefaultImpl: Foo {
        func testPrint() {
            print("Foo")
        }
    }
    
    
    extension Foo {
        
        func testPrint() {
            defaultImplementation?.testPrint()
        }
    }
    
    struct Bar: Foo {
        
        var defaultImplementation: DefaultImpl? {
            get { return DefaultImpl() }
        }
        func testPrint() {
            defaultImplementation?.testPrint() // Prints "Foo"
        }
    }
    
    struct Baz: Foo {
        func testPrint() {
            print("Baz")
        }
    }
    
    
    let bar = Bar()
    bar.testPrint() // prints "Foo"
    
    let baz = Baz()
    baz.testPrint() // prints "Baz"
    
    
    

提交回复
热议问题