[swift-evolution] Overriding protocol default implementation

Robert Ryan robert.ryan at mindspring.com
Fri Feb 10 13:41:33 CST 2017


As we all know, if you override the default implementation of a protocol, if you call the method from the protocol reference, the protocol’s default implementation will be called, not the override of that method. For example:

    protocol Fooable {
        // this is intentionally blank
    }

    extension Fooable {
        func foo() {
            print("foo")
        }
    }

    class FooBar: Fooable {
        func foo() {
            print("foobar")
        }
    }

    func performFoo(object: Fooable) {
        object.foo()
    }

    let foobar = FooBar()
    performFoo(object: foobar)      // prints “foo”, not “foobar"

But, the behavior changes you change the default method to be part of the protocol, itself:

    protocol Fooable {
        func foo()
    }

    // the rest as above

    performFoo(object: foobar)     // prints “foobar”

I would like to propose that any class that overrides a protocol’s default implementation where the method is not part of the protocol, itself, results in a warning. I’m hard pressed to think of a situation where you’d want the current Swift 3 behavior of the first example (where you can override a protocol default implementation but you only want that override used when you reference the class itself, but not when you reference the protocol as a type). If there are such examples, then add a “build setting” to allow you to turn off this warning, or add some keyword to the declaration of the default implementation that indicates that you’re allowing it to be overridden, but protocol types won’t use it (e.g. nondynamic). Personally, I’d just add the warning and call it a day (because I don’t know why you’d ever want the current Swift 3 behavior).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170210/de8197a6/attachment.html>


More information about the swift-evolution mailing list