2 Replies
      Latest reply on Jan 9, 2017 6:23 AM by KianSalem1
      KianSalem1 Level 1 Level 1 (0 points)

        I am learning Swift, and still learning the basics. I am learning about comparison operators and how they can be used to compare tuples. I am having trouble understanding this code:

        (1, "zebra") < (2, "apple")   // true because 1 is less than 2; "zebra" and "apple" are not compared
        (3, "apple") < (3, "bird")    // true because 3 is equal to 3, and "apple" is less than "bird"
        (4, "dog") == (4, "dog")      // true because 4 is equal to 4, and "dog" is equal to "dog"

        And here's the text that comes after this code :


        In the example above, you can see the left-to-right comparison behavior on the first line. Because 1 is less than 2, (1, "zebra") is considered less than (2, "apple"), regardless of any other values in the tuples. It doesn’t matter that "zebra" isn’t less than "apple", because the comparison is already determined by the tuples’ first elements. However, when the tuples’ first elements are the same, their second elements are compared—this is what happens on the second and third line.


        My question is, why does apple equal less than bird in line 2? Is this an actual comparison? Or is this just a figurative comparison? Becuase when I run this code in my playground it still evaluates to True.

        Thank you so much,


        • Re: Is this a legitimate comparison?
          eskimo Apple Staff Apple Staff (13,925 points)

          My question is, why does apple equal less than bird in line 2? Is this an actual comparison?

          Yes.  Swift’s String type conforms to the Comparable protocol by implementing a default comparison function.

          IMPORTANT Be aware that this default comparison function is not international friendly.  For example:

          print("apple" < "bird")    // prints `true`
          print("apple" < "Bird")    // prints `false`

          In most case when dealing with user-visible strings you’ll want to use use localizedCaseInsensitiveCompare(_:).  For example:

          print("\("apple".localizedCaseInsensitiveCompare("bird") == .orderedAscending)")
          print("\("apple".localizedCaseInsensitiveCompare("Bird") == .orderedAscending)")

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"