Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Operators  ›  Lesson

Arithmetic Operators

Arithmetic 12 minSwift's arithmetic operators follow multiply-before-add precedence, the remainder operator handles cycles, and compound operators update a variable in place.

Arithmetic Operators

Sprout shows "Week 3, day 2" for the 16th day of a habit, and "you are 60% of the way to your goal". Both come from a line or two of arithmetic. Swift's arithmetic looks like school maths, with two twists you need to know.

The rule

Multiply and divide before adding; % gives what is left over.

The five arithmetic operators:

let done = 3, goal = 5
done + 2        // 5
goal - done     // 2
done * 20       // 60
60 / goal       // 12   (Int division drops the fraction)
16 % 7          // 2    (16 is two weeks and 2 days)

Order. *, / and % happen before + and -, and operators of the same level go left to right. Brackets override both: (done + 2) * 10 is 50, while done + 2 * 10 is 23.

Remainder. a % b is what is left after taking out as many whole bs as fit. It is the tool for anything that cycles: days of the week, alternate rows, every third item. The sign follows the left side, so -7 % 3 is -1. For Doubles, % is not available; use a.truncatingRemainder(dividingBy: b).

Updating in place. Compound operators combine a sum and an assignment:

var streak = 4
streak += 1     // 5
streak *= 2     // 10

Swift has no ++ or --. Write += 1 and -= 1. And + also joins strings: "Day " + "3" is "Day 3".

The shortcut

To evaluate a line, circle every *, / and % and work those first, left to right, then do the + and -. For cycles, reach for %: "which day in the week?" is day % 7, and "which week?" is day / 7.

Week and day for Sprout's day 16Step 1 of 4
  1. Number the days from zero

    Day 16 counted from 1 is index 15 counted from 0. Cycles are easiest from zero.

Drills

Answer fast — trust the rule.

quick drill

What is 2 + 3 * 4?

quick drill

What is 20 % 6?

quick drill

You want to add one to streak. Which line is valid Swift?

quick drill

With var total = 10, what is total after total -= 4 and then total *= 3?

Remember

  • Multiply and divide before adding; % gives what is left over.
  • Circle *, /, % first; use / for "which cycle" and % for "where in it".
  • No ++ in Swift: write += 1.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhich week, which day?

Using / and %, explain how Sprout can turn 'day 22 of this habit' into 'Week 4, day 1'. Show the calculation and why counting from zero helps.