user3033437 user3033437 - 1 year ago 83
iOS Question

how to reorder an NSMutableDictionary of NSMutableDictionaries

In a loop with json data I'm creating an NSMutableDictionary and inside it I'm storing json parsed values :

for j in json {
var jsonValues = NSMutableDictionary()

//Create main value
guard let value = j.valueForKey("value")?.valueForKey("value")! else{

//Get name
guard let Name : String = (value.valueForKey("Name")?.valueForKey("en") as? String) else {

jsonValues["name"] = Name

//Get geoposition
guard let geoposition = value.valueForKey("geoposition") else {

//Get lat
if let lat = geoposition.valueForKey("lat") as? String {

jsonValues["lat"] = lat
let flat : Float = (lat as AnyObject).floatValue

//Get lng
if let lng = geoposition.valueForKey("lng") as? String{

jsonValues["lng"] = lng
let flng : Float = (lng as AnyObject).floatValue

let metters : CLLocationDistance = getDistance(flat, flng: flng)

jsonValues["distance"] = floor(metters)

nsDict.setValuesForKeysWithDictionary(["\(c)" : jsonValues])
c += 1

at the end of the loop I put the jsonValues mutableDictionary inside a global var, another NSMutableDictionary, named nsDict.

I would like to reorder my dictionary of dictionaries, using the
value, which is in metters, so I can show it in a tableView from lower distance to upper. I've been stackoverflowing and googling for a while, but I find only examples with
which is useless for me since I use an NSMutableDictionary. Couldn't find any example with NsMutableDictionary and doesn't really understand the apple docs. In another language, like php, I would had do this with two
But I can't manage to do it in swift 2 with the given methods . Anybody can help me?

This is an NSMutableDictionary of NSMutableDictionaries this is why I think the parsing technique is not same as to order one NSMutableDictionary

Answer Source

NSMutatbleDictionary doesn't retain order (sorted or insertion). You can't sort it.

You need a different approach, such as using an NSArray of sorted keys. See NSDictionary - Sorting Dictionaries.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download