Tuples group multiple values into a single composite value. They can be created on the fly. Values within a tuple can be of any type. They do not have to be the same type as each other. Swift 4 introduces Tuples type.
They are used many times to return multiple values from a function call.
// Tuple. var tuple1 = (1, 2, "23")
How to access the value of a tuple
We can access each of the values of a tuple by the number of the position they have within it.
You can name each of the elements of a tuple. Then, you can use the element names to access the values of those elements.
You don’t have to give your tuple elements names if you don’t want to.
When to use a Tuple in Swift
When we want to use exactly certain elements of a certain type, then you should use a Tuple. Tuples in Swift are not recommended for a complex data structure. For more complex data structures we must create a class or a structure.
Specifically, tuples are very useful as return values in functions. Let’s see an example of this.
How do I add a tuple to a Swift array?
In this example we are going to see how we can add a tuple to an array. Too easy.
Tuples Swift example
Let’s see an example of tuples in Swift. Here we can see a tuple that a server returns to us. It is a reply message. It is made up of two elements, a String and an Int, the http status codes.
You can decompose the content of a tuple into constants or separate variables, then we can access these values as normal.
In this example we see how we can access each of the values of a tuple in a single line of code.
And this is all I have to say. If I have helped you, I encourage you to leave me a comment!