[swift-evolution] Nil coalescing operator precedence

Charlie Monroe charlie at charliemonroe.net
Sun Jun 12 23:28:09 CDT 2016


+1 on this.

> On Jun 12, 2016, at 8:01 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)
> 
> An example of incorrect code from real project which went unnoticed for some time:
> 
> let allParameters: [String: Any?] =
>  defaultParameters["sendMessage"] ?? [:] +
>  parameters +
>  ["chat_id": chat_id, "text": text]
> 
> Unlike ternary operator I can hardly think of a case when someone would want to use ?? in expression like:
> a + b ?? c + d meaning (a + b) ?? (c + d) 
> 
> 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.
> 
> --
> Andrey Fidrya
> 
> _______________________________________________
> 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