Swift Programming

Swift Operator precedence and associativity

In this article you will learn about the rules used to evaluate a expression with operators and operands.

Operator precedence is a set of rules that determines which operator is executed first.

Before you learn about operator precedence, make sure to know about Swift operators.


Let’s take an example, suppose there is more than one operator in an expression.

var num = 8 + 5 * 4 // 28

Here,

  • if + is executed first, the value of num will be 52
  • if * is executed first, the value of num will be 28

In this case, operator precedence is used to identify which operator is executed first. The operator precedence of * is higher than + so multiplication is executed first.


Operator precedence table

The table below lists the precedence of Swift operators. The higher it appears in the table, the higher its precedence.

Operators Examples
Bitwise shift >> <<
Multiplicative % * /
Additive | - + - ^
Range ..< ...
Casting is as
Nil-Coalescing ??
Comparison != > < >= <= === ==
Logical AND &&
Logical OR ||
Ternary Operator ? :
Assignment Precedence |= %= /= *= >>= <<= ^= += -=

Example: Operator precedence with the complex assignment operator

var num = 15

num += 10 - 2 * 3
print(num)

Output

19

In the above example, we have created a variable num with the value 15. Notice the statement

num += 10 - 2 * 3

 

Here, the precedence order from higher to lower is *-, and +=. Hence, the statement is executed as num += 10 - (2 * 3).


Swift Operator Associativity

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left). For example,

print(6 * 4 / 3)     // 8 

Here, operators * and / have the same precedence. And, their associativity is from left to right. Hence, 6 * 4 is executed first.

Note: If we want to execute the division first, we can use parentheses as print(6 * (4/3)).


Operator Associativity Table

If an expression has two operators with similar precedence, the expression is evaluated according to its associativity.

  • Left Associativity – operators are evaluated from left to right
  • Right Associativity – operators are evaluated from right to left
  • Non-associativity – operators have no defined behavior

For example,

print (6 * 4 / 3)

Here, operators * and / have the same precedence. However, their associativity is left. Hence, 6 * 4 is executed first.

The table below shows the associativity of Swift operators.

Operators Associativity
Bitwise Shift: >> << none
Multiplicative: % * / left
Additive: | + - ^ left
Range: ..< ... none
Casting: is as none
Nil-Coalescing: ?? right
Comparison: != > < >= <= === == none
Logical AND: && left
Logical OR: || left
Ternary Operator: ? : right
Assignment: |= %= /= *= >>= <<= ^= right
Related Articles