Tuple / Named Tuple
A tuple groups multiple values into a single compound value. It is useful when you want to return multiple values from a function.
Syntax
// Create a tuple let tuple = (value1, value2, value3) // Named tuple let tuple = (name1: value1, name2: value2) // Decompose (assign each element to separate variables) let (variable1, variable2) = tuple // Access by index tuple.0 tuple.1
Syntax List
| Syntax | Description |
|---|---|
| (value1, value2) | Creates a basic tuple. Access elements by index (.0, .1). |
| (name: value, ...) | Creates a named tuple. Elements can be accessed by name. |
| let (a, b) = tuple | Decomposes a tuple and assigns each element to a variable. |
| let (a, _) = tuple | Use _ to ignore unwanted elements. |
Sample Code
// Basic tuple
let point = (10, 20)
print("x: \(point.0), y: \(point.1)")
// Named tuple
let person = (name: "Hanako", age: 25, city: "Tokyo")
print("\(person.name) (age \(person.age)) lives in \(person.city)")
// Function returning a tuple (multiple return values)
func minMax(array: [Int]) -> (min: Int, max: Int) {
return (array.min()!, array.max()!)
}
let result = minMax(array: [3, 1, 7, 2, 9])
print("Min: \(result.min), Max: \(result.max)")
// Decompose the return value
let (minVal, maxVal) = minMax(array: [5, 2, 8])
print("Min: \(minVal), Max: \(maxVal)")
// Ignore unwanted elements with _
let (_, max) = minMax(array: [4, 6, 1])
print("Max only: \(max)")
Overview
Tuples are well suited for lightweight grouping of data. They are commonly used when returning multiple values from a function or representing a temporary combination of values. Named tuples make the meaning of each element clear, improving readability.
Tuples are intended for temporary data combinations. For complex data structures or structures you use repeatedly, consider using a struct or class instead.
Tuples can also be used as multiple return values.
If you find any errors or copyright issues, please contact us.