Tuples
Sprout's weekly summary wants two answers from one calculation: which habit had the best streak, and how long it was. Making a whole new type just to hand back two values is heavy. A tuple lets you bundle them for a moment.
The rule
A tuple bundles a few values for a moment; name the parts.
A tuple is a group of values in brackets. The values can be of different types:
let best = (habit: "Read", days: 12)
print(best.habit) // Read
print(best.days) // 12
print(best.1) // 12, by position (counting from 0)The labels habit: and days: are optional, but they make code readable. Without them you are left with best.0 and best.1, and nobody remembers which is which.
You can unpack a tuple into separate names, and skip parts you do not need with _:
let (name, length) = best // name = "Read", length = 12
let (_, onlyDays) = best // just the 12The type of best is written (habit: String, days: Int). That makes tuples a natural way for a function to return more than one value:
func bestStreak() -> (habit: String, days: Int) {
("Read", 12)
}Tuples of the same shape can be compared: == checks every part, and < compares left to right, only looking at the second part when the first parts are equal.
When the grouping lasts, gets stored, or grows beyond three or so values, make a proper struct instead. Tuples are for short trips.
The shortcut
Read .0, .1 or a label by counting from zero, left to right. When writing one, ask "will this be kept and passed around the app?" If it will, it wants to be a struct; if it is used once and unpacked, a tuple is fine.
The value
let week = (habit: "Stretch", days: 5, minutes: 40).
Drills
Answer fast — trust the rule.
With let t = ("Walk", 3, true), what is t.1?
After let (_, d) = (habit: "Read", days: 7), what is d?
What does (1, "b") < (2, "a") give?
Sprout needs to store each habit's name, colour, streak, reminder and start date for the whole app. Tuple or struct?
Remember
- A tuple bundles a few values for a moment; name the parts.
- Positions count from zero; unpack with
let (a, b)and skip with_. - Stored, long-lived or many-part data belongs in a struct.
