[swift-evolution] [Idea] Use optionals for non-optional parameters

Tim Vermeulen tvermeulen at me.com
Mon Aug 15 16:09:07 CDT 2016


> On 15 Aug 2016, at 22:08, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> 
> 
> 
> On Mon, Aug 15, 2016 at 3:05 PM, Charles Srstka <cocoadev at charlessoft.com <mailto:cocoadev at charlessoft.com>> wrote:
>> On Aug 15, 2016, at 2:27 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> `let value = (x == nil) ? nil : foo.bar(x: x)` isn't so bad, is it? You could even write a custom operator to sugar it.
> 
> It’s distasteful, due to the need to use the force-unwrap operator. In cases like this, I usually end up writing:
> 
> let value: Foo? = nil
> 
> if let x = x {
> 	value = foo.bar(x: x)
> } else {
> 	value = nil
> }
> 
> or:
> 
> let value: Foo? = {
> 	if let x = x {
> 		return foo.bar(x: x)
> 	} else {
> 		return nil
> 	}
> }()
> 
> Both of which are unwieldy, but necessary to avoid the use of !.
> 
> You are arguing that the force unwrap operator ! is, per se, distasteful?

I wouldn't want ! all over my codebase, and I think the Swift language generally encourages that behaviour. In my opinion the use of ! is always caused by either a sloppy design or a language/compiler limitation. Directly comparing to nil is also something I try to avoid.

Not everyone feels this strongly about force unwrapping as I do, probably. But to me, force unwrapping is not a worthy alternative to the proposed new sugar, and I’d rather write some boilerplate code.

>  
> 
> I wouldn’t mind something like an overload on the ternary operator:
> 
> let value = x? ? foo.bar(x: x) : nil
> 
> in which a ? after the ternary condition indicates that it is an optional to be unwrapped for the positive condition.
> 
> Charles

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160815/b05149f5/attachment.html>


More information about the swift-evolution mailing list