I want the Swift version of this code:
NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.
To sort an integer array in increasing order in Swift, call sort() method on this array. sort() method sorts this array in place, and by default, in ascending order.
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
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]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With