Swift Sort string array with german localization

29 Views Asked by At

I am sorting an array of Strings in alphabetical order (first two letters) for a tableview and don't know how to sort with german localization.

When changing localization to german in xcode the sort function does puts all the "umlaut" of the second letter at the end of the second letter.

This is the output:

SORTED NAMES ARRAY ["Ebersbach, Dirk", "Essmann, Christoph", "Fallheim, Silke", "Foerster, Thomas", "Frutteln, Dr. Hans", "Förster, Prof. Dr. Farsin", "Gardeia, Christiane", "Grünelt, Mario", "Hennig, Kristin", "Hoßfeldt, Ivonne", "Lange, Kati", "Liebschwager, Georg", "Loth, Stefan", "Ludwig, Dr.Volker", "Michaelis, Nicole", "Neißhardt, Claudia", "Niepel, Mandy", "Nützer, Jens", "Patientenaufnahme D", "Patientenaufnahme FR/C", "Patientenaufnahme Ortho/BV", "Qasem, Mohammed", "Raschke, Steffen", "Riebel, Heike", "Riedel, Simona", "Schreiner, Dirk", "Seidel, Antje", "Sieler, Christian", "Zühlke, Dr. Kati"]

The sort function is this:

var bez = [String]()

let sortedBez = bez.sorted(by: {
            $0.lowercased() < $1.lowercased() } )
        

But the in the sorted output array "Förster, Prof. Dr. Farsin" (element 5 of sorted array) should come after "Foerster, Thomas" (as element 4 of sorted array).

Ho do I achieve this ? I already tried to change localization setting of xcode to german but it didn't help.

1

There are 1 best solutions below

3
Sweeper On BEST ANSWER

You can pass a String.Comparator to sort.

bez.sorted(using: String.Comparator(
    options: .caseInsensitive/*, locale: Locale(identifier: "de")*/
))

Without the locale: argument, this already sorts "Fö" immediately after "Foe". If you specifically want to use the collation rules of the German locale, you can add the locale: argument too.

You can also sort the strings in the way Finder sorts file names, by using the localizedStandard comparator:

bez.sorted(using: .localizedStandard)