atlas atlas - 1 year ago 51
Swift Question

Sort string array containing Å, Ä and Ö - Swift

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?

Answer Source

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 {
    $$1, locale: swedish) == .OrderedAscending

print(sortedTitles) // ["A", "Z", "Å", "Ä", "Ö"]

For a case-insensitive sorting, add the options: .CaseInsensitiveSearch argument.