[swift-evolution] [Proposal draft] Make Optional Requirements Objective-C-only
Charles Srstka
cocoadev at charlessoft.com
Mon Apr 25 13:12:00 CDT 2016
> On Apr 25, 2016, at 11:49 AM, Douglas Gregor via swift-evolution <swift-evolution at swift.org> wrote:
>
>> (Tangentially, why not introduce a required "override" keyword for conforming types that implement a version of a member introduced in protocol extensions? This would match the class approach and enhance safety and intent.)
>
> This is a commonly-requested feature that I don’t think we need. The TL;DR version is that I feel like specifying the conformance explicitly (my type Foo conforms to protocol P) already expresses intent, and the compiler should help with the rest. I’ve recently been working on providing better warnings for cases where one has tried to implement an optional requirement for a protocol (but got the declaration wrong), and I think we can turn it on for cases where one got a default implementation instead:
The trouble with this is that it can be quite non-obvious whether a method in a protocol is required or not. If you have this:
protocol Foo {
func bar()
func baz ()
}
extension Foo {
func bar() {}
}
it will generate this interface:
internal protocol Foo {
internal func bar()
internal func baz()
}
extension Foo {
internal func bar()
}
There’s no way to tell which method you actually have to implement, simply from looking at the protocol. When there are only two methods, this isn’t hard to figure out, but what if there are 25 methods, each with extensive header docs in front of the declaration, and only two of them are required? The only way to find the required ones would be to first completely search through the entire library and/or framework for extensions on this type. Then, you'd look at the first method in the protocol, scroll down to the extension, scour the extension for that method name, then scour any *other* extensions you’ve found for the method name, then scroll back up to the protocol, look at the next method. Now, repeat the whole thing until you’ve done it 25 times, and hope you haven’t failed to spot a method name in an extension somewhere.
The upshot of all this is that it’s pretty easy to accidentally implement a method on a protocol because you thought you had to, when actually you didn’t. Requiring “override” would at least prevent that, although IMO it would be best if there were some kind of annotation on the protocol’s interface letting you know if there were already a default implementation for that method, similar to Objective-C’s good old optional keyword.
Charles
More information about the swift-evolution
mailing list