[swift-evolution] Make distinction between ?? -> T and ?? -> T?

Jordan Rose jordan_rose at apple.com
Mon Mar 7 19:02:18 CST 2016

> On Mar 7, 2016, at 15:17, Joe Groff <jgroff at apple.com> wrote:
>> On Mar 7, 2016, at 2:26 PM, Radosław Pietruszewski via swift-evolution <swift-evolution at swift.org> wrote:
>> -1, never seen a real world situation where this would be confusing/problematic.
>> Having one operator is nice for chaining:
>> var value = someArray ?? someFallback ?? secondaryFallback ?? []
> This case could be handled by making `??` right-associative. In fact, I had originally implemented it that way. I don't recall why we changed it and added the extra overload; Jordan, do you recall?

'??' doesn't have to fold all the optionals. I consider that a feature and am happy we have it; others may disagree.

When there is a non-optional case at the end, the two versions are equivalent; they just build different intermediate closures.

(((someArray ?? someFallback) ?? secondaryFallback) ?? []) // left-associative
(someArray ?? (someFallback ?? (secondaryFallback ?? []))) // right-associative

If 'someFallback' is the first non-nil argument, then in both cases 'someArray' and 'someFallback' will be evaluated and 'secondaryFallback' and '[]' will not. With the left-associative version, we have to do extra tests for nil, but those will be optimized away when ?? is inlined. We also create more closure instances, but again we can probably optimize that away. With the right-associative version, we end up with nested closures instead, which may be harder to optimize…or may not be.


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

More information about the swift-evolution mailing list