Skip to content

Swift Operators Precedence and Associativity

New Course Coming Soon:

Get Really Good at Git

This tutorial belongs to the Swift series

Think about this expression:

let amount = 1 + 2 * 3

The value of amount could drastically change depending if 1 + 2 is calculated before 2 * 3.

The order of calculation is determined by the operator precedence. From higher precedence to lower precedence, as for the most popular operators we have:

This means that the above expression is resolved first calculating the multiplication, and then the sum:

let amount = 1 + 2 * 3 // = 7

The full table of precedence, more complicated, is available at https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations.

When inside an expression you have multiple operators with the same precedence, we make use of the operator associativity. Associativity is a property we use to determine which operation has priority when the precedence is the same.

For example, consider this:

let amount = 4 / 2 * 5

Depending if we first execute 4 / 2 or 2 * 5, the result could be 10 or 0,4.

Associativity solves this. Multiplication is left associative, so we must first execute the expression on the left. Parentheses help us figure this out:

let amount = (4 / 2) * 5

Multiplication (*), division (/), remainder (%), add (+), subtract (-), logical AND (&&), logical OR (||) are left associative

Assignment and compound assignment operators (=, += and so on) and the ternary conditional (?:) are right associative

Comparisons (==, !=, <, >, <=, >=) don’t have associativity.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: