Paradoxis Paradoxis - 1 year ago 70
Swift Question

How does the Swift string more than operator work

I don't have much experience with Swift and I come from a PHP / Python / JavaScript background, so please bare with me.

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? Thank you.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download