Potter Potter - 1 year ago 183
Swift Question

How to sort an array in Swift

How to sort an array in swift? I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Answer Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download