Sorting array alphabetically with number
Another variant is to use localizedStandardCompare:
. From the documentation:
This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate.
This will sort the strings as appropriate for the current locale.Example:
let myArray = ["Step 6", "Step 12", "Step 10"]let ans = sorted(myArray,{ (s1, s2) in return s1.localizedStandardCompare(s2) == NSComparisonResult.OrderedAscending})println(ans)// [Step 6, Step 10, Step 12]
Update: The above answer is quite old and for Swift 1.2. A Swift 3 version is (thanks to @Ahmad):
let ans = myArray.sorted { (s1, s2) -> Bool in return s1.localizedStandardCompare(s2) == .orderedAscending}
For a different approach see https://stackoverflow.com/a/31209763/1187415,translated to Swift 3 at https://stackoverflow.com/a/39748677/1187415.
The Swift 3 version of Duncan C's answer is
let myArray = ["Step 6", "Step 12", "Step 10"]let sortedArray = myArray.sorted { $0.compare($1, options: .numeric) == .orderedAscending}print(sortedArray) // ["Step 6", "Step 10", "Step 12"]
Or, if you want to sort the array in-place:
var myArray = ["Step 6", "Step 12", "Step 10"]myArray.sort { $0.compare($1, options: .numeric) == .orderedAscending}print(myArray) // ["Step 6", "Step 10", "Step 12"]
NSString has a rich set of methods for comparing strings. You can use the method compare:options:
.
You'll want the NSNumericSearch
option. If you read the description of that option, it says:
Numbers within strings are compared using numeric value, that is, Name2.txt < Name7.txt < Name25.txt.
So you could write a Swift sort line that does what you want using that function.
Something like this:
let myArray = ["Step 6", "Step 12", "Step 10"]let ans = myArray.sorted { (first, second) in first.compare(second, options: .NumericSearch) == NSComparisonResult.OrderedAscending}println(ans)// [Step 6, Step 10, Step 12]