[swift-evolution] Overriding protocol default implementation
Adrian Zubarev
adrian.zubarev at devandartist.com
Fri Feb 10 14:09:20 CST 2017
Ugh, this is a bad one, nice catch. I personally never bumped into that, but I’ll be careful from now on that one. Thanks for sharing it.
I’m interested to see the outcome of this pitch. :)
--
Adrian Zubarev
Sent with Airmail
Am 10. Februar 2017 um 20:41:57, Robert Ryan via swift-evolution (swift-evolution at swift.org) schrieb:
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).
_______________________________________________
swift-evolution mailing list
swift-evolution at swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170210/775fb99f/attachment.html>
More information about the swift-evolution
mailing list