[swift-evolution] Brainstorming: Optional sugar inferred map

Thorsten Seitz tseitz42 at icloud.com
Wed Feb 17 10:49:35 CST 2016

Optional chaining is different because of the asymmetry between receiver and arguments (Swift is using single dispatch and not multiple dispatch) and moreover because it is linear and the execution order is clear and simple to understand, i.e. when evaluating


I know that when bar() answers nil that foo() has been executed but baz() has not.

When evaluating

a.foo()? + b.bar()? * baz(c?)

I think is is much more difficult to understand what will have been executed when c answers nil, for example.


> Am 16.02.2016 um 15:10 schrieb tvermeulen via swift-evolution <swift-evolution at swift.org>:
> 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
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

More information about the swift-evolution mailing list