EN VI

Arrays - Swift Sort string array with german localization?

2024-03-17 02:30:04
How to Arrays - Swift Sort string array with german localization

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.

Solution:

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.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login