Tel Tel - 5 months ago 13
Swift Question

How to sort lines of a string in Swift?

I have a textView where I enter text, I would like to programmatically sort lines (intended here as chunks of text separated by a newline). For example:

Bravo
27
Charlie
Zulu
delta
012
Alfa
bravo
Delta


I'm trying to convert the tex to an array, then sort the array and then joying the array in a new string. Unfortunately I get unexpected results, for example words with capital letters are grouped at the beginning of the list, the ones with lowercase are listed at the end.

This is the code I'm using:

let newStr = (the field) // pseudocode

let strArray : [String] = newStr.componentsSeparatedByString("\n")
let newArray = strArray.sort { $0 < $1 }
newStr = newArray.joinWithSeparator("\n")

(the field) = newStr // pseudocode


EDIT: the result I would like to get, would be to have a sorted list taking into account local settings. In my case, for example, would be:

012
27
Alfa
bravo
Bravo
Charlie
delta
Delta
Zulu

Answer

I would solve this problem by changing your sort code to

let newArray = strArray.sort{$0.localizedCompare($1) == NSComparisonResult.OrderedAscending}

From Apple Documentation:

Important: For user-visible sorted lists, you should always use localized comparisons. Thus typically instead of compare: or caseInsensitiveCompare: you should use localizedCompare: or localizedCaseInsensitiveCompare:.

Source

Comments