Use Tuple Comparison Operators in Swift
Written by Team Kodeco
Written by Team Kodeco
In Swift, you can use comparison operators like <
, >
, <=
and >=
to compare tuples. When comparing tuples, each element is compared in the order they appear in the tuple.
Here’s an example of how to use the less than operator <
to compare two tuples:
// Example 1: Compares first element
let tuple1 = (1, "banana")
let tuple2 = (2, "apple")
if tuple1 < tuple2 {
print("Tuple 1 is less than Tuple 2")
}
if tuple2 < tuple1 {
print("Tuple 2 is less than Tuple 1")
}
// Output: Tuple 1 is less than Tuple 2
// Example 2: First element is equal, so compares second element
let tuple3 = (1, "banana")
let tuple4 = (1, "apple")
if tuple3 < tuple4 {
print("Tuple 3 is less than Tuple 4")
}
if tuple4 < tuple3 {
print("Tuple 4 is less than Tuple 3")
}
// Output: Tuple 4 is less than Tuple 3
Prev chapter
2.
Decompose Tuples in Swift
Next chapter
4.
Use Named Tuples in Swift