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
.
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]]; Your objects will be sorted according to the name property of those objects.
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.
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]];
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With