How to sort an array in Swift

Solution 1:

var names = [ "Alpha", "alpha", "bravo"]
var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

Update: Providing explanation as per recommendation of a fellow SO user.

Unlike ObjC, in Swift you have sorted() (and sort()) method that takes a closure that you supply that returns a Boolean value to indicate whether one element should be before (true) or after (false) another element. The $0 and $1 are the elements to compare. I used the localizedCaseInsensitiveCompare to get the result you are looking for. Now, localizedCaseInsensitiveCompare returns the type of ordering, so I needed to modify it to return the appropriate bool value.

Update for Swift 2: sorted and sort were replaced by sort and sortInPlace

Solution 2:

Sorting an Array in Swift

Define a initial names array:

var names = [ "gamma", "Alpha", "alpha", "bravo"]

Method 1:

var sortedNames = sorted(names, {$0 < $1})
// sortedNames becomes "[Alpha, alpha, bravo, gamma]"

This can be further simplified to:

var sortedNames = sorted(names, <)
// ["Alpha", "alpha", "bravo", "gamma"]
var reverseSorted = sorted(names, >)
// ["gamma", "bravo", "alpha", "Alpha"]

Method 2:

names.sort(){$0 < $1}
// names become sorted as this --> "[Alpha, alpha, bravo, gamma]"

Solution 3:

If your array does not contain Custom Objects (just a string or number type):

var sortedNames = sorted(names, <)

Otherwise if you create a Custom Data Object Class containing custom properties inside:

customDataObjectArray.sort({ $0.customProperty < $1.customProperty })