Search code examples
swifttuplescomparison

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!


Solution

  • 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"