I have an array with 3 names.
var patients = ["Kund Karlsson", "Test Vid behov", "Test Övrigt"]
I need to sort these names alphabetically. This is the result its supposed to be ordered in.
I sort the array like this patients.sort({ $0 < $1 })
but I get the wrong order.
I assume this is caused by that unicode letter Ö
.
Is there a way handle sorting when you have unicode characters in strings?
Thank you.
I guess the Ö is treated as O in English, but thats might not be true for all languages. You can use the following:
patients.sort {
$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedDescending
}
Results depends on you system's locale. To use specific locale:
var patients = ["Kund Karlsson", "Test Vid behov", "Test Övrigt"]
let locale = NSLocale(localeIdentifier: "sv_SE")
patients.sort {
let str1 = $0 as NSString
let str2 = $1 as NSString
return str1.compare(str2, options: .CaseInsensitiveSearch, range: NSMakeRange(0, str1.length), locale: locale) == NSComparisonResult.OrderedAscending
}