Tuples
A tuple groups multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
Creating Tuples
Tuples are created by wrapping comma-separated values in parentheses.
// Unnamed elements
let person = ("John", 30)
// Named elements (Recommended for readability)
let pirate = (name: "Jack Sparrow", rank: "Captain")Accessing Elements
Elements in a tuple can be accessed using zero-based index numbers or by their names if they were provided.
let user = ("Alice", 25)
print(user.0) // "Alice"
print(user.1) // 25Decomposing Tuples
You can "decompose" a tuple’s contents into separate constants or variables.
let httpError = (404, "Not Found")
let (code, message) = httpError
print("The code is \(code)")
print("The message is \(message)")If you only need some of the tuple's values, use an underscore (_) to ignore parts of the tuple when decomposing it.
let (statusCode, _) = httpError
print("Status code is \(statusCode)")Returning Multiple Values
Tuples are particularly useful as return types for functions that need to return more than one piece of information.
func getDimensions() -> (width: Int, height: Int) {
return (1920, 1080)
}
let size = getDimensions()
print("Width: \(size.width), Height: \(size.height)")When to use a Tuple?
Tuples are best used for temporary groupings of related values. Their most common and powerful use case is returning multiple values from a function.
TIP
Use a tuple for simple, short-lived data structures. If your data structure needs to persist or has complex logic, use a Struct or Class instead (covered later).
Tuples vs Collections
Later in this book, you will learn about collections (like Arrays and Dictionaries), which are designed to safely group multiple items together. While tuples also group data, they behave very differently.
Fixed Size
Once you create a tuple, its size is locked. You cannot add or remove elements later, whereas standard collections can grow and shrink dynamically.
Mixed Types
Standard collections usually hold items of the exact same type, like a list containing only strings. A tuple is specifically built to hold different types together safely, like a string, an integer, and a boolean all in one package without any extra setup.
No Iteration or Helpers
Because a tuple is just a simple, temporary container, you cannot loop through its elements using a for-in loop. Tuples also do not have access to built-in helper tools like counting elements, filtering out data, or sorting.
