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

Matthew Johnson matthew at anandabits.com
Sat Apr 2 07:25:56 CDT 2016

Sent from my iPad

> On Apr 2, 2016, at 7:04 AM, Lukas Stabe via swift-evolution <swift-evolution at swift.org> wrote:
> All use-cases I had for optional methods in protocols in Objective-C are covered nicely by providing a default implementation in a protocol extension, so I don't think optional protocol methods should be a thing in pure Swift.
>> I do not understand why an optional method should require a default value. That’s not how optional methods work in Objective-C where the caller will ask whether the method is implemented and calls it or does something else. With a default value it would be much more difficult to do something different if the method is not implemented.
>> Actually with a default value the method would just be a normal method which has not been overridden, there would be nothing optional about it anymore.
> I've actually had multiple cases in Objective-C code where this feature (some object behaving differently depending on wether or not a delegate method has been implemented) has prevented me from implementing features the easy and obvious way. In those cases I resorted to implementing 'respondsToSelector:'. So I'd argue that optional protocol methods encourage this type of behavior, which imho is bad API design. If you need to behave differently for some types of delegates (or whatever else your protocol represents), a separate method to call to determine how to behave is much simpler and better to use.

+1.  This is exactly the same thing I mentioned regarding the fast path for row height in UITableView.  The fact that it depends on whether or not the delegate implements heightForRowAtIndexPath is a bad design decision.

> – Lukas
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

More information about the swift-evolution mailing list