1

I was reading the documentation on the Swift programming language, when I came across the following code snippet:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

func backwards(s1: String, _ s2: String) -> Bool {
   return s1 > s2
}

names.sort(backwards) // ["Ewa", "Daniella", "Chris", "Barry", "Alex"]

What I don't seem to be able to find, is how the > operator works in this context, I thought it would do something like count the amount of characters and then return a boolean based on that, but with that logic the following snippet should return false:

"CD" > "ABC" // true

Could someone please explain what is going on here?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
Paradoxis
  • 4,077
  • 6
  • 28
  • 65
  • what is your current knowledge / understanding of string comparison? – Wain Jul 12 '16 at 13:52
  • @Wain I've only ever used basic `==`, `===`, `!=` in other languages, so seeing a more than / less than being used is quite new – Paradoxis Jul 12 '16 at 13:53

2 Answers2

1

I believe javascript uses exactly the same string comparison approach, and the same syntax. In javascript you could also use localeCompare(). And in swift you could alternatively use localizedCompare(_:) (or one of the other string comparison functions). They're all different ways, and with different options, to alphabetically compare strings.

Wain
  • 118,043
  • 14
  • 134
  • 151
  • 2
    Addition, Swift 2.2.30: from the [String.swift source code](https://github.com/apple/swift/blob/master/stdlib/public/core/String.swift) we can see that e.g. the ` – dfrib Jul 12 '16 at 14:34
0

Swift does lexicographical string comparison. This has been asked before you can check it out here

Community
  • 1
  • 1
Dickson Leonard
  • 498
  • 4
  • 14