Sort NSArray with sortedArrayUsingComparator

Paulo Rodrigues picture Paulo Rodrigues · Sep 10, 2014 · Viewed 23k times · Source

In Objective-C I can sort an NSArray using this statement:

NSArray *sortedArray = [persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
    return [p1.name compare:p2.name];
}];

I'm unable to reproduce the same statement with Swift. All I found was using Array.

Answer

Mike S picture Mike S · Sep 10, 2014

You can either use Swift's built in sort functions or, since a Swift array is bridged to NSArray you can call sortedArrayUsingComparator from swift directly.

Using Swift's sorted function:

var sortedArray = sorted(persons) {
    (obj1, obj2) in

    // The downcast to Person is only needed if persons is an NSArray or a Swift Array of AnyObjects
    let p1 = obj1 as Person
    let p2 = obj2 as Person
    return p1.name < p2.name
}

Or, using NSArray's sortedArrayUsingComparator:

var sortedArray = persons.sortedArrayUsingComparator {
    (obj1, obj2) -> NSComparisonResult in

    let p1 = obj1 as Person
    let p2 = obj2 as Person
    let result = p1.name.compare(p2.name)
    return result
}