Sort NSArray of NSDictionary objects in Swift

21,526

Solution 1

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])

Solution 2

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"]!
}
Share:
21,526
jopeek
Author by

jopeek

Updated on July 09, 2022

Comments

  • jopeek
    jopeek almost 2 years

    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?

  • Kyle Rosenbluth
    Kyle Rosenbluth almost 10 years
    Alternatively, this can be done on one line: var sortedResults= results.sorted { $0["name"]! > $1["name"]! }
  • ColinE
    ColinE almost 10 years
    It can indeed, but I am guessing the OP is a little new to Swift, so I opted for a more verbose closure syntax!
  • jopeek
    jopeek almost 10 years
    I am indeed new to Swift and I did try this earlier but couldn't make it work. I think I see what I missed though and will give your answer a shot later on. Thank you!
  • jopeek
    jopeek almost 10 years
    I'm sure this would have worked but I had all kinds of trouble bridging from NSArray to Array... Kambala's answer below worked though so I could keep using the NSArray.
  • Alejandro Luengo
    Alejandro Luengo over 9 years
    Using xcode 6.1 this gives me an 'Cannot convert the expression's type '$T7?? to type 'NSSortDescriptor' because I defined the NSArray like this var valores = NSMutableArray(contentsOfFile: file) Any advice please? Any help will be much welcome
  • Shankar Raju
    Shankar Raju almost 9 years
    How would you do the same with multiple sort descriptors?
  • Unome
    Unome over 8 years
    Fantastic solution! Thx.
  • RikiRiocma
    RikiRiocma about 8 years
    Great! the only example working after searching for 2 days! Thanks a lot.
  • Markus
    Markus over 7 years
    If you have this in Objective-C -> NSArray *array = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)]; Anybody knows the alternative in Swift?