What are tuples in Swift?
Tuple in Swift
A Tuple in Swift is a group of different values that are used to return multiple values from a function call.
They are also referred to as ordered and comma-separated lists of values that are wrapped in parentheses.
Basic tuple
The values of a tuple can be of different data types. A basic tuple that groups together a String and an Integer is shown below:
var device = ("Android", 500)
Named tuple
We can also define a tuple by naming its elements. We use these names to access the elements of a named tuple as described below:
var student = (name: "John", age: 21)
print(student.name)
Output
John
Nested tuple
Tuples created as an element of another tuple are referred to as Nested Tuples.
An example is shown below:
var alphaNum = ("x", 1, 2, ("y", 3, "z"))
In the example above, we have a tuple ("y", 3, "z") as the third element of the created alphaNum tuple.
Tuple elements
The elements of a tuple are similar to those of an array. They are represented by index numbers.
The first element is at index 0 and the second element is at index 1.
The indexing continues in this order.
To access the elements of a tuple, we use their respective index numbers.
An example is shown below:
var cityRatings = ("London", 7)print("City:", cityRatings.0)print("Ratings:", cityRatings.1)
Output
City: London
Ratings: 7
A tuple named cityRatings was created in the code above. The elements were accessed using their index numbers.
We can also update the elements of a tuple by assigning a new value to the particular index to be modified.
An example is shown below:
var book = ("The Geo book", 1000)print("Original Tuple:")print("Name:", book.0)print("Pages:", book.1)// modify second valuebook.1 = 1500print("After Modification:")print("Name:", book.0)print("Pages:", book.1)
Explanation
A tuple named book is created in the example above, and its value is modified at index 1 from 1000 pages to 1500 pages.