A tuple is nothing more than a grouping of values. You can use it anywhere you can use a type.
let x: (String, Int, Double) = ("hello", 5, 0.85)
To access the elements in the tuple we can assign names to them and pull them out one by one.
let (word, number, value) = x
print(word) // prints hello
print(number) // prints 5
print(value) // prints 0.85
A cleaner way to do the above would be to name the elements when the tuple is declared.
let x: (w: String, i: Int, v: Double) = ("hello", 5, 0.85)
print(x.w) // prints hello
print(x.i) // prints 5
print(x.v) // prints 0.85
We can also use tuples as a return type for a function.
func getSize() -> (weight: Double, height: Double) {
return (250, 80)
}
let x = getSize()
print("weight is \(x.weight)") // weight is 250
// or
print("height is \(getSize().height)") // height is 80
Notice that we don't need to specify the element names in the return statement of the func.