[swift-evolution] [Proposal] Make optional protocol methods first class citizens

Sean Heber sean at fifthace.com
Fri Apr 1 09:12:42 CDT 2016

>> None taken. However, most of the delegate concept of UIKit relies heavily on this "nonsensical" requirement. It is impossible for someone to implement a control in swift which is "in the spirit" of UIKit, meaning the control has a delegate, with several methods that share the same name with different parameters, some are required and some are optional. I think it is not fair to tell users that they cannot implement something that is such a common and repeating pattern in the core. 
> Protocol requirements with default (no-op) implementations already satisfy that design goal, no?
> -Chris

I agree that’s the case, but what happens for situations like UIKit where I do not have access to the source? If there is a protocol extension for, say, UITableViewDelegate that implements default behaviors, that extension’s existence might be publicly declared somewhere so I could know, but the implementation bodies would not be, correct? So as a user of UITableViewDelegate and without access to UIKit’s source code, I cannot examine the protocol extension to see what the extension is *actually* doing by default. The situation is then no better than it is now where the information about the default behavior or result of a missing delegate function is buried somewhere in the documentation. If the protocol spec itself included the “effective” default and there was no way to provide a default implementation that did anything *except* return a value (or do nothing), then the protocol declaration itself documents the intent and I, as an external user of UITableViewDelegate without access to the source code, could see exactly what it does.

Perhaps my understanding/reasoning there is flawed, but that's why I continue to suggest something like this:

protocol MyProtocol {
  default func semiOptionalFunctionA() -> Int = 42  // if unspecified, compiler generates implementation that returns 42
  default func semiOptionalFunctionB(thing: Int)   // if unspecified, compiler generates implementation that does nothing
  func normalRequiredFunction()   // requires an implementation by the user


More information about the swift-evolution mailing list