Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 146 ยท Control Flow

Tuples

Learn Swift tuples - create them, read elements by index or name, decompose into variables, return several values from a function, compare tuples and know when a struct is better.

Sometimes two or three values belong together for a moment, but not long enough to deserve their own type: a minimum and a maximum, a status code and a message, the x and y of a point you are about to throw away. Swift's answer is the tuple, a lightweight group of values that you can create, pass around and take apart in a single line.

A tuple is a value type with a fixed number of elements, and each element can have a different type. You have already met tuples when you switched over several values at once in switch and when you looped with enumerated() in Loops. This lesson shows how they work, where they shine and where a real type is the better choice.

Creating and reading tuples

Write the values in parentheses, separated by commas. The type of the tuple is the list of the element types, and Swift infers it for you.

Swift Your first tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The elements are numbered from zero, and you read them with a dot and the index: response.0. The type prints as (Int, String), which tells you something important: the tuple's shape is part of its type. A (Int, String) and a (String, Int) are different types and cannot be mixed up by accident.

A tuple is also a value, so it is copied when you assign it. Changing one copy never touches the other. To change an element, the tuple must be a var:

Swift Tuples are values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both original and copy start equal, then each is changed on its own. If you declared frozen with var and never changed it, Swift would warn you; with let the whole tuple is constant, element by element.

Naming the elements

Numbers like .0 and .1 get unreadable fast. You can give each element a label, either when you create the tuple or in its type annotation. The labels are part of the type, and the index syntax still works.

Swift Named elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice person.2 still works, because a named element is also an indexed one. When you annotate the type as (x: Double, y: Double), you can create the value with plain (3.0, 4.0) and the labels attach automatically.

Swift lets you convert between a labeled and an unlabeled tuple of the same shape, but labels that disagree are an error, as the last example of this lesson shows.

Decomposing a tuple

The best feature of tuples is decomposition: you split a tuple into separate constants or variables in one statement. The pattern on the left has the same shape as the tuple on the right.

Swift Decomposing into variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The underscore throws away the part you do not need. Tuples can be nested, and a pattern can reach into the nesting. You can also use var to get mutable copies, as with low and high.

The last two loops are decomposition at work. enumerated() produces a sequence of (offset:element:) tuples, and a Dictionary produces (key:value:) tuples. The loop variable pattern (index, letter) takes each one apart. That is why for (key, value) in dictionary feels so natural in Swift.

You can also swap two values without a temporary variable, which is a classic use of a tuple on both sides of the assignment:

Swift Swapping with tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The whole right side is evaluated first, then assigned. That is why (a, b) = (b, a) works and why the Fibonacci step uses the old values on the right.

Returning several values from a function

A function normally returns one value. When a calculation naturally produces several results, return a tuple. This is the most common use of tuples in everyday Swift. It is also a first look at functions.

Swift Returning a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The return type (min: Int, max: Int)? is an optional tuple, because an empty array has no minimum. The guard var line is the usual way of taking the first element safely. We call Swift.min and Swift.max with the module name because the tuple labels min and max would otherwise be confusing in this scope. Inside divide, the body is a single expression, so no return keyword is needed.

The caller can read the result by label (result.min) or decompose it (let (q, r) = ...). Many small helper functions of your own will benefit from the same idea.

Comparing tuples

Tuples of up to six elements can be compared with ==, < and the other operators as long as every element type is comparable. Comparison goes element by element from the left, the way you compare words in a dictionary: the first differing element decides.

Swift Comparing and sorting tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The sort trick in the last line is worth remembering. To order by age first and then by name, compare two derived tuples: (age, name) < (age, name). You get a multi-key sort without writing nested if statements. Comparison is a standard-library feature for tuples up to arity six, which is plenty for sort keys.

Tuples are not Equatable or Hashable in the protocol sense, which means you cannot put them in a Set or use them as Dictionary keys directly. You can compare them with the operators, and the compiler provides those operators as special overloads. If you need a key made of several values, define a small struct and see Equatable, Hashable and Comparable.

Tuples and pattern matching

Because a tuple is just a few values in a row, switch can match them with ranges, wildcards and bindings. This is the same material as in switch, but now with a purpose: decide on two inputs at once.

Swift Tuples in a switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Matching on a tuple built on the spot, (n % 3, n % 5), is a very Swift way to write a small decision table. The next lesson, Pattern Matching, digs into every kind of pattern.

When tuples go wrong

Tuples are for short-lived, local groupings. They have limits you should know about.

  • No methods, no conformances. A tuple cannot have behavior, and you cannot make it conform to a protocol. If the data needs a method, an invariant or Codable, use a struct.
  • Labels carry little meaning at API boundaries. A public function returning (Int, Int, Int) forces every caller to guess what the numbers are. Named elements help, but a struct with documentation helps more.
  • The shape leaks into the signature. Add a fourth value to a returned tuple and every caller that decomposes it breaks. A struct can gain a field without breaking the callers that ignore it.
  • They are copied, not shared. That is usually good, but a large tuple of large values gets copied as a whole.

The compiler also protects you from misusing labels. This code assigns a tuple to a variable whose labels have different names:

Swift Mismatched labels (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects the assignment: main.swift:2:33: error: cannot convert value of type '(width: Int, height: Int)' to specified type '(w: Int, h: Int)'. Names are not just comments, they are checked. To relabel the values, take the tuple apart and build a new one: (w: measured.width, h: measured.height). (Merely reordering the same labels currently compiles with a deprecation warning, which will become an error in a future language mode, so do not rely on it.)

A good rule of thumb: if you return a tuple from a function that is used in more than a couple of places, or you find yourself writing the same tuple type twice, turn it into a struct.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the value (404, "Not Found")?

    A tuple type lists the element types in order, so the value has the type (Int, String). The order is part of the type.
  2. 2. Which statement splits a tuple into two constants and ignores the second element?

    A tuple pattern on the left of the assignment decomposes the value, and the underscore discards the part you do not need.
  3. 3. What does (2, "a") < (1, "z") evaluate to?

    Tuples are compared from the left. The first elements differ (2 versus 1), so that comparison decides and the later elements are never looked at.
  4. 4. When is a struct a better choice than a tuple?

    Tuples cannot have methods or conform to protocols, and their shape leaks into every signature. A named type is better for data with meaning or a longer life.
  5. 5. Which line swaps the variables a and b without a temporary?

    The right side is evaluated completely before it is assigned, so (a, b) = (b, a) swaps the values. The first option leaves both variables equal.

Summary

  • A tuple groups a fixed number of values of possibly different types: (404, "Not Found") has the type (Int, String).
  • Read elements by index (t.0) or by label (t.name); labels are part of the type and are checked by the compiler.
  • Decompose a tuple with a matching pattern: let (a, _) = t; loops over enumerated() and dictionaries do this for you.
  • Return several results from a function with a tuple, optionally with labels or as an optional tuple.
  • Tuples up to six elements compare lexicographically with == and <, which gives a neat multi-key sort.
  • Tuples are values with no methods or protocol conformances; use a struct for anything bigger or longer-lived.

Next: Pattern Matching