What are tuples in Swift ?

Here we are again. Let’s take a look at tuples in swift. We can think of tuples as a container that contains different values with different types. That means the elements in the tuple don’t have to be in the same type. Below there is a simple definition :

var user = ("vedat","ozlu",26,179)

In the preceding line of code we have a user tuple. First value is the name, the second one is the surname, the others are age and height values. We can access the value of tuples with the index numbers. user.0 will give you the first value of tuple and so on.To make that user tuple more readable we can also define it like this :

var user = (name :"vedat",surname :"ozlu", age :26, height: 179)

I think the preceding line is clearer than the first one right ? This definition is also called named tuples. We can print each of these element values like this :

print(user.name)
print(user.surname)
print(user.age)
print(user.height)

Tuples are very useful for many purposes. For example if you have a class or structure that only contains some variables to store data then we can use tuples instead. Of course if your class or structure also contains methods then you cannot use tuples. Tuples are also useful if we want to return multiple values from a function. That is pretty cool. So let’s take a look at an example to see how we can return multiple values from a function :

import Foundation
 
func getUser()->(String,String,Int,Int) {
    return ("Vedat","Ozlu","26","179")
}
 
var user = (name : "", surname : "", age : 0, height : 0)
user = getUser()
 
print(user.name)
print(user.surname)

When we run the code we can see that the output will be like “Vedat\n” “Ozlu\n” . We can also get each of the returning values into separate variables. Below code shows how to do that :

import Foundation
 
func getUser()->(String,String,Int,Int) {
    return ("Vedat","Ozlu","26","179")
}
 
var (name,surname,age,height) = getUser()
print(name)
print(username)

When you run the preceding code the output will be the same. Alright. This was the basic explanation of tuples in swift. I hope it was useful for you too. See you in another post. Peace..

You may also like...