Yevhen Kovalov
Yevhen Kovalov

Reputation: 21

Swift tuples comparison

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

Answers (3)

gnasher729
gnasher729

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

Robin Schmidt
Robin Schmidt

Reputation: 1203

In both cases the numeric value is equal.
The difference is the string comparison:

  • "life" is < "lifiee", because "e" is < "i"
  • "life" is > "death", because "l" is > "d"

String comparison works letter by letter, until letters aren't equal or one string is and end. For example:

  • "a" < "b", because "a" is earlier in alphabet than "b"
  • "a" < "ab", because "a" is shorter than "ab"
  • "aa" == "aa"

So for your tuple:

  • {1, "a"} < {2, "a"} => 1 < 2
  • {1, "a"} < {1, "b"} => 1 == 1 && "a" < "b"

Upvotes: 0

Ahmad F
Ahmad F

Reputation: 31655

Eventually, let's remind that for comparing tuples, they should have:

  • The same number of values.
  • The same types.

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

Related Questions