How to use tuples in Swift

Tuples in Swift are very lightweight data types which enable you to create, store and pass around groups of values which can be of different types. This can be very useful when trying to return multiple values from a function in Swift as a single compound value.

Creating tuples

How to define a basic tuple which groups together an integer and a string:

let myTuple: (Int, String) = (7, “Seven”)

Tuple’s type definition can be omitted because the compiler will figure it out for you:

let myTuple = (7, “Seven”)

Tuples can also be defined by naming individual elements:

let city = (name: "Hood River", population: 7167)

Reading values from tuples

Decompose a tuple into separate variables or constants:

let (cityName, cityPopulation) = city

You can ignore parts of the tuple with an underscore:

let (cityName, _) = city

You can access individual elements of the tuple using indexes:

let cityName = city.0
let cityPopulation = city.1

Or, if you defined the tuple by naming individual elements, you can use element names:

let cityName = city.name
let cityPopulation = city.population

Using tuples as return values of functions

Tuples are extremely useful when trying to return multiple values from a function. Take a look at this example function which groups together two values (a String and an Int) and returns them as one tuple with named elements:

func getCity() -> (name: String, population: Int) {
    return ("Hood River", 7167)
}

Reading the return value of the getCity() function looks like this:

let myCity = getCity()
print("Name: \(myCity.name), Population: \(myCity.population)")

Related tutorials: