Calling protocol default implementation from regular method

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

    In case your protocol has associatedType or Self requirements, then the cast will not work. To work around this, create a "shadow" default implementation that both the regular default implementation and the conforming type can call.

    protocol Foo { 
        associatedType Bar
    }
    
    extension Foo {
        func testPrint() {
            defaultTestPrint()
        }
    }
    
    fileprivate extension Foo { // keep this as private as possible
        func defaultTestPrint() {
            // default implementation
        }
    }
    
    struct Bar: Foo {
        func testPrint() {
            // specialized implementation
            defaultTestPrint()
        }
    }
    

提交回复
热议问题