Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Tuples in Swift
Written by Team Kodeco

In Swift, a tuple is a group of multiple values represented as one value. Tuples are handy when you need to return multiple values from a function or to store multiple values in a single variable.

To create a tuple, use parentheses and separate the values with commas. Here’s an example of declaring a tuple that holds a name and an age:

let person = ("Alice", 25)

You can also use type annotations to specify the types of the values in a tuple:

let person: (String, Int) = ("Alice", 25)

Accessing Tuple Values

You can access the values of a tuple using index numbers. The index numbers start from 0. Here’s an example of how to access the values of person:

let name = person.0 // Alice
let age = person.1  // 25

You can also use named tuple elements to access the values of a tuple. Here’s an example of how to use named tuple elements to access the values of person:

let (name, age) = person
print(name) // Alice
print(age)  // 25

Using Tuples in Functions

You can use tuples to return multiple values from a function. Here’s an example of a function that uses a tuple to return a person’s name and age:

func getPerson() -> (String, Int) {
  return ("Alice", 25)
}
let person = getPerson()
© 2024 Kodeco Inc.