1.11 Tuples
Tuples are a way of grouping multiple values into a single compound values. As such, they are very useful in functions that need to return several distinct. See the Functions section for more information. For example, the following Tuple is of type (Int,String)
and represents an HTTP Status Code:
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
There is no restriction on the number or permutation of types you can have within a Tuple. (Int,Int,Int)
, (Bool, [String])
and any other permutation are equally valid.
Tuples possess a special syntax which allows them to be easily decomposed:
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
If you do not need access to all the parts of a Tuple, you can omit some using the _
syntax:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"
You can also access the elements of a tuple using indices:
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"
Finally, you can also name the inidividual elements of a tuple on declaring it.
let http200Status = (statusCode: 200, description: "OK")
You can then use those names to access the values of those elements:
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"