Create & Use Tuples in Swift
Written by Team Kodeco
A tuple in Swift is a group of related values that can be stored together. They are similar to arrays, but unlike them, the elements of a tuple can be of different types. They are also lightweight and can be used to store small amounts of data.
To create a tuple, use parentheses and separate the elements with commas. Here is an example of creating a tuple that contains a string, an integer and a boolean:
let myTuple = ("Hello", 42, true)
You can also create a tuple by manually specifying the type:
let myTuple: (String, Int, Bool) = ("Hello", 42, true)
You can access the elements of a tuple by their index:
let firstElement = myTuple.0
let secondElement = myTuple.1
let thirdElement = myTuple.2
Alternatively, you can access the elements of a tuple by using pattern matching:
let (firstElement, secondElement, thirdElement) = myTuple
print(firstElement) // Output: "Hello"
You can think of a tuple as a shopping bag that contains multiple items. Each item may be different, but they are all related and are stored together in the same bag.
The rest of this section of the cookbook will go into more detail about how to use Tuples in Swift.