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 // 10Swift 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.
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.
What is 2 + 3 * 4?
What is 20 % 6?
You want to add one to streak. Which line is valid Swift?
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.
