[swift-evolution] Brainstorming: Optional sugar inferred map

tvermeulen tvermeulen at me.com
Tue Feb 16 08:10:45 CST 2016


But wouldn’t you say optional chaining is almost the same thing?  I’m a bit puzzled why people say this new proposal makes the code confusing, while the current implementation of optional chaining isn’t frowned upon.

let a: String? = "123"
let b: String = "456"
let c = a?.stringByAppendingString(b)

This works as expected.

let a: String = "123"
let b: String? = "456"
let c = a.stringByAppendingString(b?)

This, however, does not work. I think the only reason the second example seems a bit off is because we’re not used to it, but both seem equally readable to me. The second example is basically equivalent to this:

let a: String = “123”
let b: String? = “456”
let c = b?.stringByPrependingString(a)

Which would work, if only there is no such function. I guess the point I’m trying to make is that currently, whether we have to use a lot of boilerplate code depends on the choice of receiver and argument of the function, which could be completely arbitrary.

> > To address this, the nil-coalescing operator would allow $$, where $$ is the unwrapped unnamed result of the expression when non nil:
> > 
> > func doSomething(value: Int) ->Int {
> > return value
> > }
> > 
> > let ra = a ?? doSomething($$)
> > let rc = c ?? doSomething($$)
> > 
> > ra ->5
> > rc ->nil
> I think this is completely the wrong way to approach this.
> 
> *If* you want to implement this feature, I think the way to do it is to say that you can put ? after any optional parameter to a normal function call, and Swift will unwrap all the parameters so marked and make the call return `nil` if any of them are nil.
> 
> let ra = doSomething(a?)
> let rc = doSomething(c?)
> 
> Naturally, since operators are just function calls with a funny syntax, this would also extend to operators.
> 
> a? + b // a.k.a. +(a?, b)
> 
> Even in this form, however, I don't think this is a feature worth having. Too indirect and specialized.
> 
> --
> Brent Royal-Gordon
> Architechies
> 
> 
> 
> 


More information about the swift-evolution mailing list