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"]!
}
Author by
jopeek
Updated on July 09, 2022Comments
-
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 almost 10 yearsAlternatively, this can be done on one line:
var sortedResults= results.sorted { $0["name"]! > $1["name"]! }
-
ColinE almost 10 yearsIt can indeed, but I am guessing the OP is a little new to Swift, so I opted for a more verbose closure syntax!
-
jopeek almost 10 yearsI 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 almost 10 yearsI'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 over 9 yearsUsing 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 almost 9 yearsHow would you do the same with multiple sort descriptors?
-
Unome over 8 yearsFantastic solution! Thx.
-
RikiRiocma about 8 yearsGreat! the only example working after searching for 2 days! Thanks a lot.
-
Markus over 7 yearsIf you have this in Objective-C -> NSArray *array = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)]; Anybody knows the alternative in Swift?