Search code examples
swiftoperatorsoperator-precedence

Swift trouble with operator priority


UPDATED

Expression: a ?? 0 + b, where a is CGFloat?, b is CGFloat and a != nil.

Concrete example:

//a == 99
//b == 253
let t = ((a ?? 0) + b)
let t2 = (a ?? 0 + b)
//t == 352
//t2 == 99

Why the result is correct if I set brackets only: (a ?? 0) + b


Solution

  • Both results are “correct.” They can be different because + has a higher precedence than ??. In particular, if a != nil:

     t  == (a ?? 0) + b == a! + b
     t2 == (a ?? 0 + b) == a ?? (0 + b) == a!
    

    The complete list of operator precedences can be found at Operator Declarations.