Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Swift's Data Types  ›  Capstone Project

Tuples

Tuples 12 minA tuple groups a few values of possibly different types for a short time, accessed by label or zero-based position and unpacked with let.

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 12

The 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.

Unpacking Sprout's weekly bestStep 1 of 4
  1. The value

    let week = (habit: "Stretch", days: 5, minutes: 40).

Drills

Answer fast — trust the rule.

quick drill

With let t = ("Walk", 3, true), what is t.1?

quick drill

After let (_, d) = (habit: "Read", days: 7), what is d?

quick drill

What does (1, "b") < (2, "a") give?

quick drill

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.

Practice — level up

0/1 solved

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

ExplainTuple or struct?

Give one situation in Sprout where a tuple is the right tool and one where a struct would be better. Explain what makes the difference.