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…

  • Swift dictionary bug?
  • Expected Declaration error creating array in ViewController, can't work out why
  • Why does the same method fail when inside an Array extension in Swift?
  • UIImage Loop Through Pixel Highly Inefficient?
  • Swift: different objects in one array?
  • Can I change an NSDictionaries key?
  • 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?

    3 Solutions Collect From Internet About “Sort NSArray of NSDictionary objects in Swift”

    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"]!
    }
    
    var arrDescriptor = NSSortDescriptor(key: "", ascending: true)
       var sortDescriptors: NSArray = [arrDescriptor]
       _sortedArray = allKeysArray.sortedArrayUsingDescriptors(sortDescriptors as [AnyObject])
    
       print(_sortedArray)