Sunday, July 14, 2019

Default compare operator on swift tuple type

Swift standard library defineds tuple comparison operators for tuple with fewer than seven elements.
In order to compare two tuples, they must have the same type and the same number of values. Tuples are compared from left to right, one value at a time. If the comparison finds two values are equal, then it move to the next element to decide the overall compare result. If all elements are equal, then the two tuples are equal.

  1. (1, "zebra") < (2, "apple")
  2. // true because 1 is less than 2; "zebra" and "apple" are not compared

  3. (3, "apple") < (3, "bird")
  4. // true because 3 is equal to 3, and "apple" is less than "bird"

  5. (4, "dog") == (4, "dog")
  6. // true because 4 is equal to 4, and "dog" is equal to "dog"


As a result, the common comparison operators can be directly applied to tuple array as shown below

var numberStrings = [(2, "two"), (1, "one"), (3, "three")]
numberStrings.sort(by: <)
numberStrings // [(1, "one"), (2, "two"), (3, "three")]

No comments:

Post a Comment