[swift-evolution] Will Swift ever support optional methods without @objc?

Haravikk swift-evolution at haravikk.me
Tue Nov 15 05:22:00 CST 2016


> On 15 Nov 2016, at 07:53, Rick Mann via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Nov 14, 2016, at 22:51 , Charlie Monroe via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> One major example is the NS/UITableViewDataSource or Delegate - there are many many methods that you don't need to implement, hence are optional.
>> 
>> But I think that this was partially solved by default implementation of protocol methods, which pretty much does what you want...
> 
> I just realized I only responded to someone else, and not the whole list. It does, but it forces me to make the return value of the protocol method optional, so that the default implementation can return nil. 
> 
> In the end, I guess that's not so bad, since I'm not happy with the entire approach, but it'll do for now.

What's different about having the method return nil vs being optional? You're attempting to call it either way, and presumably need some means of handling the return value, except in Swift it's all nice and explicit and easy to put in a conditional like:

	if let result = myObject.someOptionalMethod() { /* Do some stuff */ }
	print(myObject.someOptionalStringMethod() ?? "")

And so-on. If you need a method to be both optional, and return a nilable result then you can use a double optional like so:

	if let result = myObject.someDoubleOptionalMethod() { // Method was implemented
		if let value = result { // Method returned a value
			/* Do some stuff */
		}
	}


By defining the methods as returning an Optional and throwing in default implementations you can specify fewer, bigger protocols and make clear what the requirements really are, though personally given the choice I'd prefer a dozen smaller protocols that are absolutely explicit in what they do.

But yeah, I think the tools you need are all there already; maybe there's an argument to be made for allowing default return values on protocol methods, to reduce the boiler-plate?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161115/e0aea347/attachment.html>


More information about the swift-evolution mailing list