Swift should have a keyword to mark a protocol method as optional, every solution right now feels like a band aid which doesn't fix the problem. @objc isn't great, a protocol extension with an empty implementation is better, but still not great. This feels like Swift should have a keyword to mark a section or individual methods as optional

@cocoasamurai why isn’t a default implementation identical and nicer? Forcing the function itself to be optional (ie requiring optional chaining) feels annoying.

@cocoaphony it accomplishes the desired effect, but it doesn't communicate it very well. ObjC protocols do this very easily at the time of protocol declaration with the optional & required keywords, no further source code or documentation reading is required to understand what you do, or don't have to implement.

Follow

@cocoasamurai But Cocoa needs this heavily because it relies so much on the delegate pattern. I'm finding (at least in my code) that Swift has much better patterns than delegate. Completion handlers and smaller strategy objects (and bare functions) IMO are better tools in Swift. Cocoa has moved more this way, too. Massive delegates w/ lots of optionals is, I'm coming to believe, indicating a problem rather than something to make more streamlined. 1/

@cocoasamurai This isn't a really strongly-held opinion. I've thought a lot about how I would redesign UITableView and WKWebView without optional-heavy delegates, and I don't have a great answer there. But in day-to-day Swift I'm seeing people reach for delegates in many cases where they shouldn't, so I'm also concerned about creating attractive nuisances and ever-more optionals (as in the `?` kind, which I think are also overused).

I don't really have the answer here.

@cocoaphony yeah really I just want some official way to signal (without documentation or having to see an empty method implementation in a protocol extension) that you don't have to implement a method. I don't do this a lot, so I'd like to keep these methods (required & not) in the same protocol. It's also possible I need to rethink my design a bit to avoid needing the optional methods all together 🤷🏻‍♂️

Sign in to participate in the conversation
Mastodon

Follow friends and discover new ones. Publish anything you want: links, pictures, text, video. This server is run by the main developers of the Mastodon project. Everyone is welcome as long as you follow our code of conduct!