Protocols and Default Implementations


Rick Aurbach
 

Suppose I have a protocol that contains a method with a default implementation:
 
    public protocol A {
        func foo()
    }
    
    public extension A {
        func foo() {
            print("A.foo()")
        }
    }
 
Now in a class that conforms to this protocol, I know I can call the method (and get the default implementation) or override the method (and get my own implementation).
 
QUESTION: Is it possible to EXTEND the default implementation. What I'd like to do is write something like:
 
    class X : A {
        func foo() {
            A.foo()
            print("X.foo()")
        }
    }
 
    X.foo() // prints
            // "A.foo()"
            // "X.foo()"
 
This does not, of course, compile. But you can see what I want to do.

Is this possible? If so, how? (The alternative seems to be to repeat the default implementation everywhere we customize the method, which is a real mess if we ever change the content of the default implementation.)
 

Join {cocoa@apple-dev.groups.io to automatically receive all group messages.