Values and types

Swift Tuples

Learn how to use tuples in Swift to group several values together, name and decompose their elements, return multiple values, and even swap variables.

This tutorial belongs to the Swift series

A tuple groups multiple values into a single value. For example, we can describe a dog with a String for the name and an Int for the age:

let dog: (String, Int)

And we can initialize it with both values:

let dog: (String, Int) = ("Roger", 8)

As with any other variable, Swift can infer the type at initialization, so you usually write:

let dog = ("Roger", 8)

Reading the elements

You can access each element by position, starting from 0:

let dog = ("Roger", 8)
dog.0 // "Roger"
dog.1 // 8

Positions are hard to read once you have more than two values. Six months from now, dog.1 tells you nothing. It’s better to name the elements:

let dog = (name: "Roger", age: 8)

dog.name // "Roger"
dog.age  // 8

Decomposing a tuple

You can also split a tuple into separate constants in one line:

let dog = ("Roger", 8)
let (name, age) = dog

Now name is "Roger" and age is 8. If you only need one of the values, put an underscore where the others go:

let dog = ("Roger", 8)
let (name, _) = dog

The _ tells Swift to ignore that position. Without it you’d get a warning about an unused age constant.

When to use tuples

Tuples are a great tool for a few needs.

The first is a quick way to group related data without defining a new type. If you keep passing the same two or three values around together, that’s a tuple.

The second is returning multiple values from a function. A function can only return one thing, so you return a tuple:

func dogInfo() -> (name: String, age: Int) {
    return ("Roger", 8)
}

let info = dogInfo()
print(info.name) // Roger
print(info.age)  // 8

The third is swapping two variables:

var a = 1
var b = 2

(a, b) = (b, a)

// a == 2
// b == 1

Without tuples you’d need a temporary variable. Here Swift builds the tuple (2, 1) on the right and assigns it back into a and b in one step.

One caution: tuples are for small, temporary groupings. If the same tuple starts showing up in many places, or you wish it had methods, define a struct instead. We’ll cover structs later in the course.

Lesson completed