Why aren’t optional members for protocols supported in general?

Why is this a legacy Objective-C feature? The main problem with making it general is figuring out the interface for the receiver to know if a given member is actually implemented or not.

Inspired by the “property wrapper” feature having an optional member (for proxy support).

Note that if you’re not doing anything more than to call it if it’s there, you can provide default implementation which does nothing.

2 Likes

I’ve generally found it more semantically expressive to make one protocol without the method and another protocol conforming to the first that adds the method because usually the method being there or not has meaning worth expressing with the naming of the protocols.

I can imagine a case where the existence of an optional method does not hold enough weight to warrant a new protocol, but I’m not sure if I have run into that scenario.

1 Like

I have written a blog article on a way of having that kind of functionality in Swift protocols:

I'm not sure how I would find a reference, but I seem to remember the original decision basically being "Lets see if it's actually needed". The way Protocols and Extensions work in Swift is fundamentally different from Objective-C and it can be limiting to bring the previous thought process into a new paradigm. Having the ability to have a protocol hierarchy and extensions solve a lot of the same problems as optional requirements.

In my own experience, the times I've wanted optional requirements have been better expressed by multiple protocols or having one adhere to another.

1 Like
Terms of Service

Privacy Policy

Cookie Policy