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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Paradoxis
  • 4,471
  • 7
  • 32
  • 66
  • 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

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

Community
  • 1
  • 1
Dickson Leonard
  • 518
  • 5
  • 14
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,658
  • 15
  • 128
  • 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 `<` operator for `String` is defined as `lhs._compareString(rhs) < 0` (which use `_swift_stdlib_unicode_compare_utf8_utf8`, itself), which we can track via https://github.com/apple/swift/blob/master/stdlib/public/stubs/UnicodeNormalization.cpp to `ucol_strcollIter` (see `MakeRootCollator` for collator) from [ICU lib](http://icu-project.org/apiref/icu4c/ucol_8h.html); i.e., using [unicode collation](http://unicode.org/reports/tr10/). – dfrib Jul 12 '16 at 14:34