Reputation: 21
Can someone tell, why in similar cases Xcode returns: in 1st case - true, in 2nd case - false? It's a tuples comparison. First it compares Integers, but how does it compare Strings?
(5, "life") < (5, "lifiee")// true
(99, "life") < (99, "death")// false
Thanks for your answers in advance!
Upvotes: 1
Views: 386
Reputation: 52592
Tuple comparison compares the first, second, etc. element until it finds two elements that are not equal. Then it returns the comparison result for these two elements. If all elements are equal then the tuples are equal.
(5, x) < (6, y) returns true whatever x, y are because 5 < 6; the first element is different.
(5, x) < (5, y) returns the same result as x < y, because the first elements are the same, so the second elements are compared.
Upvotes: 1
Reputation: 1203
In both cases the numeric value is equal.
The difference is the string comparison:
String comparison works letter by letter, until letters aren't equal or one string is and end. For example:
So for your tuple:
Upvotes: 0
Reputation: 31655
Eventually, let's remind that for comparing tuples, they should have:
Based on that, tuples are compared from left to right sequentially until a mismatch found.
In the first example:
(5, "life") < (5, "lifiee")
5 and 5 are equals, so we jump to the next two values to compare, which are "life" and "lifiee"; Therefore:
"life" < "lifiee"
is true
, which means the final result is true
.
In the second example:
(99, "life") < (99, "death")
99 and 99 are equals, so we jump to the next two values to compare, which are "life" and "death"; Therefore:
"life" < "death"
is false
, which means the final result is false
.
For taking a deeper look of how the comparison is done, you could check Tuple comparison operators proposal:
@warn_unused_result
public func < <A: Comparable, B: Comparable, C: Comparable>(lhs: (A,B,C), rhs: (A,B,C)) -> Bool {
if lhs.0 != rhs.0 { return lhs.0 < rhs.0 }
if lhs.1 != rhs.1 { return lhs.1 < rhs.1 }
return lhs.2 < rhs.2
}
Upvotes: 1