Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array in Swift

Tags:

swift

I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
like image 727
Potter Avatar asked Aug 09 '14 21:08

Potter


People also ask

How do you sort an array of data in Swift?

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.

How do I sort an int array in Swift?

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.


2 Answers

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

like image 106
MirekE Avatar answered Oct 21 '22 21:10

MirekE


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]" 
like image 20
Selva Avatar answered Oct 21 '22 20:10

Selva