[swift-evolution] Nil coalescing operator precedence

Andrey Fidrya af at zabiyaka.com
Sun Jun 12 01:01:17 CDT 2016

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:

I propose to consider raising it's precedence or requiring parentheses if ?? is used with multiple statements.

Andrey Fidrya

More information about the swift-evolution mailing list