Tuples Swift
What are tuples ?
Tuples group multiple values into a single compound value. The values within a tuple can be of any type and don’t have to be of the same type as each other.
Here we are going to see about the various types of Tuples structuring, dismantle (decompose) and tuple comparison. Naming or positioning are the key for any tuple.
Structuring
Tuples can be created/structured using the below ways
Option 1: Simple Comma “,”
Simple grouping separated with commas “,”
let http404Error = (404, “Not Found”)
Option 2: Naming elements
Naming the individual elements
let http200Status = (statusCode: 200, description: “OK”)
Decomposing
As like structuring there are couple of ways to access the tuple elements,
Options 1: Using Index
Access the individual element values in a tuple using index numbers starting at zero
let http404Error = (404, “Not Found”)
let code = http404Error.0
let message = http404Error.1
Option 2: Element name
Using element names to access the elements
let http200Status = (statusCode: 200, description: “OK”)
let code = http200Status.statusCode
let message = http200Status.description
Option 3: Value binding
let http404Error = (404, “Not Found”)
let (justTheStatusCode, _ ) = http404Error
justTheStatusCode is now 404. Parts of the tuple with an underscore (_
) is ignored.
Comparison
You have two golden rules to compare tuple
- Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal.
2. If all the elements are equal, then the tuples themselves are equal
Those two values are compared, and the result of that comparison determines the overall result of the tuple comparison. . For example
- (1, “zebra”) < (2, “apple”) // true because 1 is less than 2; “zebra” and “apple” are not compared — Rule 1, 1 and 2 are unequal and 1 < 2 is true
- (3, “apple”) < (3, “bird”) // true because 3 is equal to 3, and “apple” is less than “bird” — Rule 1, because 3 is equal to 3 it goes to the next value until the comparison finds two values that aren’t equal i.e checks “apple” and “bird” where “apple” < “bird” is true
- (4, “dog”) == (4, “dog”) // true because 4 is equal to 4, and “dog” is equal to “dog” — Rule 2
Fact: Swift can compare only upto seven values in a tuple
Reference