Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray of NSDictionary objects in Swift

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?

like image 443
jopeek Avatar asked Jul 10 '14 19:07

jopeek


2 Answers

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])
like image 107
kambala Avatar answered Nov 06 '22 03:11

kambala


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"]!
}
like image 12
ColinE Avatar answered Nov 06 '22 05:11

ColinE