Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
atlas Avatar asked Aug 02 '16 12:08

atlas


People also ask

How do I sort an array of strings in Swift?

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.

How do I sort an array element in Swift?

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.

How do you sort an array of strings?

To sort an array of strings in Java, we can use Arrays. sort() function.

How do you sort an array in ascending order in Swift 4?

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.


1 Answers

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", "Å", "Ä", "Ö"]
like image 72
Martin R Avatar answered Oct 17 '22 18:10

Martin R