Search code examples
arrayssortingswiftunicodeunicode-string

Sorting an array with unicode strings


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.

  1. Kund Karlsson
  2. Test Vid behov
  3. Test Övrigt

I sort the array like this patients.sort({ $0 < $1 }) but I get the wrong order.

  1. Kund Karlsson
  2. Test Övrigt
  3. Test Vid behov

I assume this is caused by that unicode letter Ö.

Is there a way handle sorting when you have unicode characters in strings?

Thank you.


Solution

  • 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
    }