I have retrieved some JSON data from an API and now have an NSArray full of NSDictionary objects. Each NSDictionary has a key/value pair of "name" and I want to sort the NSArray by that key/value pair.
I've done quite a bit of searching but none of the solutions I've come across seem to work in the new Swift language and I'm not sure if it's possibly a bug or not...
I've tried:
var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors(NSSortDescriptor(key: "name", ascending: true))
But that won't compile stating "NSSortDescriptor is not convertible to [AnyObject]".
Any advice?
you must pass an array of sort descriptors (even if it's only one):
var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])
Rather than doing this the old way, why not embrace the new? The swift Array type has both sort
and sorted
methods. You can supply a closure as the sort function:
var sortedResults= results.sorted {
(dictOne, dictTwo) -> Bool in
// put your comparison logic here
return dictOne["name"]! > dictTwo["name"]!
}
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