Start learning free

LESSON 20 OF 349 · CALCULATIONS WITH NUMBERS

Operator Precedence in Swift in Swift

Lesson

TL ; DR:

  • When we string operations together, Swift must know which one to do first. This is called operator precedence.


  • * and / are performed before + and -:

  • print(1 + 2 * 3) // Prints 7
    print(6 - 4 / 2) // Prints 4
    print(5 * 4 - 2 / 2) // Prints 19
    

  • We can add () to force an operation to be performed first:

    print((1 + 2) * 3) // Prints 9
    print((6 - 4) / 2) // Prints 1
    print(5 * (4 - 2) / 2) // Prints 5
    


Full lesson:

When we string operations together, Swift must know which one to do first. This is called operator precedence.

This is the hierarchy from highest precedence to lowest precedence:

  • Parentheses are always respected
  • Exponentiation (raise to a power)
  • Multiplication, Division and Remainder
  • Addition and Subtraction
  • Left to right


First example:

print(1 + 2 * 3) // Output: 7

Multiplication is executed before addition, so:

1 + 2 * 3 = 1 + 6 = 7

Second example:

print((1 + 2) * 3) // Output: 9

What's inside parentheses is executed before multiplication, so:

(1 + 2) * 3 = 3 * 3 = 9

Third example:

print(6.0 / 4.0 * 3.0 + 5.0) // Output: 9.5

Multiplication and division come before addition. Also, multiplication and division have the same priorty so they are executed from left to right:

6 / 4 * 3 + 5 = 1.5 * 3 + 5 = 4.5 + 5 = 9.5

Forth example:

print(6 / ((4 + 2) / 3)) // Output: 3

Computer sees parentheses so it looks at it like this:

6 / ((4 + 2) / 3) = 6 / x, where x = (4 + 2) / 3

I have to compute x first. Parantheses are executed before division:
(4 + 2) / 3 = 6 / 3 = 2

I can replace x with 2:
6 / ((4 + 2) / 3) = 6 / 2 = 3


Assignment
Follow the Coding Tutorial and let's practice with operator precedence!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Operator Precedence in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free