Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray with sortedArrayUsingComparator

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.

like image 846
Paulo Rodrigues Avatar asked Sep 10 '14 15:09

Paulo Rodrigues


People also ask

How do I sort NSArray?

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]]; Your objects will be sorted according to the name property of those objects.

How do you sort an array of objects in Objective C?

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.

How do you sort a string array in Objective C?

For just sorting array of strings: sorted = [array sortedArrayUsingSelector:@selector(compare:)]; For sorting objects with key "name": NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]];


1 Answers

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 } 
like image 196
Mike S Avatar answered Sep 20 '22 21:09

Mike S