Start learning free

LESSON 265 OF 678 · TUPLES, SORTING & BUILT-INS

Tuples in Swift

Lesson

TL ; DR:

A tuple keeps a few values together, like a movie's title and year. Give its parts labels and read them with a dot, or unpack them into constants.


let movie = (title: "Frozen", year: 2013)   // a tuple with labels
print(movie.title)                          // Frozen
print(movie.1)                              // 2013, by position

let (title, year) = movie                   // unpacking
print("\(title) \(year)")                   // Frozen 2013


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. A tuple keeps a few values like these in one constant.

  • (title: "Frozen", year: 2013) makes a tuple with labels. Its type is (title: String, year: Int).
  • movie.title reads a part by its label. movie.0 and movie.1 read it by its position.

let (title, year) = movie unpacks the tuple into two new constants. It works like for (name, points) in scores.

A function can return a tuple. Its return type is the tuple's type, like (title: String, year: Int). The caller unpacks it or reads result.title.

A tuple made with let can't be changed. With var, movie.year = 2014 works. Still, a tuple never gets more parts, and its types stay fixed.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make splitTime return its tuple: the whole hours and the minutes left.

Then unpack pet into name and age.

Last, call splitTime(135). Unpack its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check