How to sort an array in Swift

I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
+42
swift
Aug 09
source share
8 answers
 var names = [ "Alpha", "alpha", "bravo"] var sortedNames = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending } 

Update: Provide explanations as recommended by another SO user.

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

Update for Swift 2: sorted and sort have been replaced by sort and sortInPlace

+67
Aug 09 '14 at 21:29
source share
— -

Array Sort in Swift

Define an array of initial names:

 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:

 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]" 
+20
Jan 06 '15 at 19:09
source share

If your array does not contain user objects (just a string or number type):

 var sortedNames = sorted(names, <) 

Otherwise, if you create a user data object class containing user properties inside:

 customDataObjectArray.sort({ $0.customProperty < $1.customProperty }) 
+17
Dec 19 '14 at 11:40
source share

The most efficient way to sort in SWIFT

Using Operator overloading is the most efficient way to sort strings in Swift.

 // OPERATOR OVERLOADING let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var sortedNames = sorted(names, <) var reverseOrder = sorted(names, >) 

In the above > and < commands, the operators are overloaded in Swift to sort the lines.

I tested the code on the Playground and came to the conclusion that when using operator overloading, it is best to sort the lines.

Copy below on the Playground.

 let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversed = sorted (names, // This is a closure { (s1 : String, s2 : String) -> Bool in return s1 > s2 } ) println(reversed) var reverseOrder = sorted(names, {s1, s2 in s1 > s2}) var reverseOrder2 = sorted(names, { $0 > $1} ) // OPERATOR OVERLOADING var reverseOrder3 = sorted(names, >) 

Conclusion from the playground:

enter image description here

From the above image, you can see that all other methods should list the loops to sort 5 lines. Where, as when using Operator overload, it is not necessary to enumerate a loop to sort the lines.

Link from Swift documentation

+7
Jan 22 '15 at 10:27
source share

If you want to sort the array in ascending order, use the syntax below:

 var arrayName = sorted(arrayName, <) 

since sorted () is a predefined function in swift and <is used to indicate that the array should be sorted in ascending order. If you want to sort the array in descending order, just replace < with as below:

 var arrayName = sorted(arrayName, >) 
+4
Jul 30 '15 at 7:27
source share

You can usually use the built-in

 func sort<T : Comparable>(inout array: [T]) 

but if you want to use localizedCaseInsensitiveCompare: your code can be translated directly using NSArray .

+2
Aug 09 '14 at 21:07
source share

Any method that can be used with Objective-C sortedArrayUsingSelector: can be used with Swift sort (or sorted ), provided that the type of the item in the array is known. So in your code:

 var arr : [String] = // ... // it is an array of String, so we can use localizedCaseInsensitiveCompare: sort(&arr) {return $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending} 

Similarly:

 var events : [EKEvent] = // ... sort(&events) {return $0.compareStartDateWithEvent($1) == .OrderedAscending} 
+2
30 oct. '14 at 10:55
source share

In Swift -

 let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] let sortedStudents = students.sorted() print(sortedStudents) // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" 

To sort the elements of your sequence in descending order, pass the greater (>) operator to the sorted (isOrderedBefore :) method.

 let descendingStudents = students.sorted(isOrderedBefore: >) print(descendingStudents) // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" 
+1
Jun 20 '16 at 12:07 on
source share



All Articles