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"]