In Swift programs, tuples can combine related data. When looping over a dictionary, we access the data as tuples. To return multiple values in a method, we return a tuple.
The syntax for tuples in Swift is simple and concise. We just specify the values we want to be a part of the tuple, in parentheses.
Here we create a tuple with a String
and an Int
. We access the first item in the tuple with the expression entry.0
. And the second item is at index 1.
// Create a tuple with two items. let entry = ("cat", 100) // Access item 0 and item 1. let name = entry.0 let number = entry.1 // Display name, number and entire tuple. print(name) print(number) print(entry)cat 100 (cat, 100)
A tuple is a "composition" of multiple values. So when we decompose a tuple, we break
it apart (unpack it) into its smallest parts.
let color = ("Green", 822, 0) // Decompose the tuple to unpack its items into variables. // ... An underscore means no variable. let (name, code, _) = color print(name) print(code)Green 822
Indexes are fine for some tuples. But for more complex ones, we can provide names for the items in a tuple upon creation. We can then reference those names.
// Use named items in tuple. let language = (name: "Ruby", speed: 0, usability: 10) // Access named items in tuple. print("\(language.name) has speed of \(language.speed)") print("\(language.name) has usability of \(language.usability)")Ruby has speed of 0 Ruby has usability of 10
To return many values at once, a method can return a tuple. Here we return two Ints from a func
. No inout parameters are needed.
func computeData(x: Int) -> (Int, Int) { // This func returns a tuple. return (x * 2, x * 100) } // Get tuple from method. let result = computeData(x: 3) print(result)(6, 300)
A tuple can be switched upon. We specify all the elements in each case in the switch
statement. Here is the simplest syntax form.
switch
must have the correct "tuple pattern" with a matching number of elements.let value = ("bird", 100) // Switch on the tuple. switch (value) { case ("bird", 100): print("Bird 100") default: print("Unknown") }Bird 100
switch
This example uses the "let" keyword to capture a value in a tuple switch
. The "let animal" value is the first item in a tuple. The second item must be 100 to match.
let value = ("elephant", 100) // Use let to capture a variable in a tuple. switch (value) { case (let animal, 100): print("\(animal) has value 100") default: print("Default") }elephant has value 100
This is another tuple switch
feature. We can use the underscore to match any value in a tuple's item. We switch
on the third item in a tuple in this example.
let elements = ("aa", "bb", 2) // Match complete tuple values. switch (elements) { case (_, _, 1): print("Third value is 1") case (_, _, 2): print("Third value is 2") default: print("Error") }Third value is 2
Tuples are a core part of the Swift language. They are used throughout code. They reduce complexity by composing multiple items into one.