46

I want the Swift version of this code:

NSArray *sortedNames = [names sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
1
  • Check developer.apple.com/swift for basics (including sorting) var sortedStrings = sorted(stringArray) { $0.uppercaseString < $1.uppercaseString } Commented Apr 8, 2015 at 9:14

8 Answers 8

73
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

Sign up to request clarification or add additional context in comments.

8 Comments

Please explain how this code works. This minimizes the tendency to copy and paste without clear understanding.
There's definitely no "sorted" method, should be sort. I verified on Swift2.0
@Jacky - yes, it changed in Swift 2
It works only if I use sort() instead of sorted. I'm using Xcode 7.3. Can't say if the result is the intended in the original code.
@Tel - the original code is pre-Swift 2.0. There is an update from 2015 that states that you need to use sort instead of sorted in Swift 2
|
22

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]"

1 Comment

var names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var sortedNames = sorted(names, {$0 < $1}) print(sortedNames) var sortedNames2: () = names.sort(){$0 < $1} print(sortedNames2) Why is sortedNames2 returning an empty array?? Thanks
17

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 })

Comments

7

Most efficient way of sorting in SWIFT

The use of Operator Overloading is the most efficient way to sort Strings in Swift language.

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

In above code > and < operators are overloaded in Swift to sort Strings.

I have test the code in Playground and conclude that when we use operator overloading it is best for sorting Strings.

Copy below to 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, >)

The conclusion from Playground:

enter image description here

From above image you can see that all other ways needs to enumerate loops for sorting 5 strings. Where as when we use Operator overloading it does not required to enumerate loop to sort strings.

Referenced from Swift documentation

Comments

4

If you want to sort your array in ascending order then use below syntax:

var arrayName = sorted(arrayName, <)

as the sorted() is the 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 then simply replace < with > as I have shown below:

var arrayName = sorted(arrayName, >)

1 Comment

In swift 2: arrayName = arrayName.sort(>)
2

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.

Comments

2

Any method that can be used with Objective-C sortedArrayUsingSelector: can be used with Swift sort (or sorted) provided the type of thing 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}

1 Comment

There's an obvious pattern here, and it would be nice to express that pattern so that you can convert the selector to a Swift function automatically, but I don't see how to do it.
1

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-than operator (>) to the sorted(isOrderedBefore:) method.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.