I'm trying to sort a string array alphabetically. With the standard sort function it works when the string does not contain Å, Ä or Ö (Swedish).
I want to order it like A...Z, Å, Ä, Ö. Instead the order produced is A...Z, Ä, Å, Ö.
I tried to use localizedCompare, but did not get it to work. In this case Å and Ä was translated to 'A' and Ö to 'O'.
let songs = self.allSongs.sort { return $0.title.localizedCompare($1.title) == .OrderedAscending }
Any ideas on how to do this?
Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator ( < ). To sort the elements of your sequence in descending order, pass the greater-than operator ( > ) to the sorted(by:) method. The sorting algorithm is not guaranteed to be stable.
To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.
To sort an array of strings in Java, we can use Arrays. sort() function.
To sort an integer array in increasing order in Swift, call sort() method on this array. sort() method sorts this array in place, and by default, in ascending order.
I want to order it like A...Z, Å, Ä, Ö
That is the ordering as defined in the Swedish locale, so you have to set it explicitly if the current locale is not Swedish:
let titles = [ "Z", "Ö", "Å", "Ä", "A" ]
let swedish = NSLocale(localeIdentifier: "sv")
let sortedTitles = titles.sort {
$0.compare($1, locale: swedish) == .OrderedAscending
}
print(sortedTitles) // ["A", "Z", "Å", "Ä", "Ö"]
For a case-insensitive sorting, add the options: .CaseInsensitiveSearch
argument.
Update for Swift 3:
let titles = [ "Z", "Ö", "Å", "Ä", "A" ]
let swedish = Locale(identifier: "sv")
let sortedTitles = titles.sorted {
$0.compare($1, locale: swedish) == .orderedAscending
}
print(sortedTitles) // ["A", "Z", "Å", "Ä", "Ö"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With