Swift Tuples
A tuple groups several values into one compound value. The values can have different types, and a tuple has a fixed number of elements. Tuples are perfect for small, temporary groupings — like returning both a minimum and a maximum from a function — without defining a whole new type.
Creating and reading tuples
Access elements by position with .0, .1, .2…
let httpError = (404, "Not Found")
print(httpError.0)
print(httpError.1)
print(httpError)
print(type(of: httpError))404
Not Found
(404, "Not Found")
(Int, String)
Named elements
Giving elements names makes code much easier to read:
let product = (name: "Keyboard", price: 49.99, inStock: true)
print(product.name)
print(product.price)
print(product.inStock ? "Available" : "Sold out")
print(product.0) // positions still workKeyboard
49.99
Available
Keyboard
Decomposing a tuple
You can unpack a tuple into separate constants or variables in one line. Use _ for elements you don't need:
let point = (x: 3, y: -7, z: 12)
let (x, y, z) = point
print("x = \(x), y = \(y), z = \(z)")
let (_, height, _) = point
print("Only the y value: \(height)")
// Swapping two variables with a tuple
var a = "left"
var b = "right"
(a, b) = (b, a)
print(a, b)x = 3, y = -7, z = 12
Only the y value: -7
right left
Returning multiple values from a function
The most common real use: a function that needs to return more than one thing.
func stats(of numbers: [Int]) -> (min: Int, max: Int, average: Double) {
var low = numbers[0]
var high = numbers[0]
var sum = 0
for n in numbers {
low = min(low, n)
high = max(high, n)
sum += n
}
return (low, high, Double(sum) / Double(numbers.count))
}
let result = stats(of: [8, 3, 12, 5, 7])
print("min \(result.min), max \(result.max), average \(result.average)")
let (lo, hi, _) = stats(of: [100, 40, 70])
print("Range: \(lo)–\(hi)")min 3, max 12, average 7.0
Range: 40–100
Tuples in loops and comparisons
Dictionaries and enumerated() hand you tuples, which you decompose right in the loop header. Tuples of comparable values can also be compared with ==, < and friends — element by element, from left to right:
let results = [("Mia", 92), ("Leo", 85), ("Ava", 92)]
for (name, score) in results {
print("\(name) scored \(score)")
}
print((1, "b") < (2, "a")) // decided by the first element
print((2, "a") < (2, "b")) // first equal, so the second decides
print((3, "x") == (3, "x"))
// Sort by score (descending), then by name
let ranking = results.sorted { ($1.1, $0.0) < ($0.1, $1.0) }
print(ranking.map { $0.0 })Mia scored 92
Leo scored 85
Ava scored 92
true
true
true
["Ava", "Mia", "Leo"]
Tuples in a switch
Because a switch can match patterns, tuples let you branch on two values at once:
let lights = [(true, false), (false, true), (true, true)]
for (wifi, bluetooth) in lights {
switch (wifi, bluetooth) {
case (true, true): print("Wi-Fi and Bluetooth on")
case (true, false): print("Only Wi-Fi on")
case (false, true): print("Only Bluetooth on")
case (false, false): print("Airplane mode?")
}
}Only Wi-Fi on
Only Bluetooth on
Wi-Fi and Bluetooth on
When to use a tuple — and when not
| Use a tuple when… | Use a struct when… |
|---|---|
| grouping 2–3 values briefly | the data has a clear identity or is passed around a lot |
| returning several values from a function | you need methods, protocols or more than a few fields |
| swapping or decomposing values | the grouping appears in many places of your code |
Tip: If you notice the same tuple type, say
(name: String, price: Double), appearing in several places, it's time to turn it into astruct.
Test yourself
Given let t = (name: "Ana", age: 30), which expression gives 30?
- t[1]
- t.age
- t.1 and t.age both work
- t.get(1)
What does let (_, b) = (5, 9) do?
- Assigns 5 to b
- Assigns 9 to b and ignores 5
- It's a compile error
- Creates a tuple named b
Is (2, "z") < (3, "a") true or false?
- true
- false
- It doesn't compile
- It depends on the string