[swift-evolution] Nil coalescing operator precedence

Andrey Fidrya af at zabiyaka.com
Tue Jun 14 17:50:43 CDT 2016


I've given it some more thought... Even expressions with single ?? can be confusing.
For example:

1)

let z = a ?? x + y + z

Actually it's
let z = a ?? (x + y + z)

But can be mistakenly interpreted as
let z = (a ?? x) + y + z

2) Same problem with ?:

let z = a ? b : c + x + y

It's
let z = a ? b : (c + x + y)

Not
let z = (a ? b : c) + x + y

Possibly warnings should be shown in both these cases. Or is it too extreme?

--
Andrey Fidrya



> On 15 Jun 2016, at 01:08, Roth Michaels via swift-evolution <swift-evolution at swift.org> wrote:
> 
> On Sun, Jun 12 2016 at 02:01:17 AM, Andrey Fidrya via swift-evolution <swift-evolution at swift.org> wrote:
>> Nil coalescing operator has very low precedence and it's very easy to forget the parentheses.
>> It's tempting to write something like this:
>> 
>> let result = v1 ?? 0 + v2 ?? 0
>> 
>> Which will resolve to
>> 
>> let result = v1 ?? (0 + v2 ?? 0)
> 
> This is how I would expected the operator to work.
> 
>> This seems to be a source of errors in other languages as well, for example:
>> http://www.codeproject.com/Tips/721145/Beware-The-null-coalescing-operator-is-low-in-the
>> 
>> I propose to consider raising it's precedence or requiring parentheses if ?? is used with multiple statements.
> 
> I like the idea of requiring parenthesis (or at least having a warning)
> on ambiguous lines with two `??`.
> 
> --
> Roth
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list