1

I declared the following array in my playground

var stringArray = ["a","A","@c","&","!","f","G","h"]

when I tried to sort it using (since String conforms to Comparable)

stringArray = stringArray.sorted(by: { $0 < $1 })

I got the following result

["!", "&", "@c", "A", "G", "a", "f", "h"]

however, if I declared it as

stringArray = stringArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

I will get a different result

["!", "@c", "&", "A", "a", "f", "G", "h"]

The results are not the same.

Why this behavior happens?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
A.Munzer
  • 1,890
  • 1
  • 16
  • 27
  • Related: [What does it mean that string and character comparisons in Swift are not locale-sensitive?](https://stackoverflow.com/questions/25713975/what-does-it-mean-that-string-and-character-comparisons-in-swift-are-not-locale) – Martin R Nov 07 '17 at 08:02

1 Answers1

1

Different locales may have different sorting orders for characters. You should use this when you are presenting a sorted list to the user.

Using localizedCaseInsensitiveCompare makes sure that if you have a list that you are presenting to the user, it is sorted using the current locale, in a way that the user expects.

Marcel
  • 6,393
  • 1
  • 30
  • 44