[swift-evolution] Keyword for protocol conformance
Charles Srstka
cocoadev at charlessoft.com
Fri Aug 26 13:27:18 CDT 2016
> On Aug 26, 2016, at 11:02 AM, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
>
> Really? I wasn't aware that you could work around the `override` keyword (the one that's required for classes). How do you do that?
By implementing the subclass’s method before the superclass’s. You can try this yourself:
- - - Library code: - - -
open class Superclass {
public init() {}
public func foo() {
print("foo called in library")
}
}
- - - App code: - - -
import FooLibrary
class Subclass: Superclass {
func bar() { print("bar called in the app") }
}
let obj = Subclass()
obj.foo()
- - - output: - - -
foo called in library
Program ended with exit code: 0
- - - - - -
Now: Change the library code to:
open class Superclass {
public init() {}
public func foo() {
print("foo called in library")
bar()
}
// Hey look, I didn't even use that stupid new 'open' keyword.
public func bar() { print("bar called in library") }
}
- - - Run the app again without compiling it, and: - - -
foo called in library
bar called in the app
Program ended with exit code: 0
- - -
Voilà: I overrode a method (a supposedly non-overridable one, at that) with no “override” keyword. Just as File A in your earlier example can implement a protocol method without realizing it, Subclass here has unintentionally overridden a superclass method. This is because ‘override’ does not, to the best of my knowledge, mean anything to the actual machine code that is produced; rather, it signals the developer’s *intent,* thus allowing the compiler to assist in making sure the developer does the right thing.
I’d actually argue that the example above is a much, much bigger problem than the objection you raised, as it can actually produce unintended behavior at runtime, whereas the example with protocols can’t.
As for the protocol example, I’d like to refine Option 3 from last night slightly:
Option 4: A keyword is required on a method declaration if and only if the containing type is declared as conforming to its protocol, either in its definition or in an extension that is visible within the current scope. This allows the extension to remain empty in your example, but puts the responsibility on the developer to declare conforming methods when it is reasonable to know that they will satisfy a protocol.
Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160826/9b0ac559/attachment.html>
More information about the swift-evolution
mailing list