ios - Sorting array of dictionaries by value after for loop? -


i've seen lot of answers similar questions none of methods have worked far.

if let users = snapshot.value!["users"] as? dictionary<string,anyobject> {   each.users = int(users.count)  var pointsarray = [dictionary<string,int>]()    (key, value) in users {                 let uid = key               let points = value["points"] as! int               pointsarray.append([uid : points])                          } 

i'm needing sort pointsarray "points", sort high low, grab 0th (highest) element, grab uid use.

i've tried:

  var myarr = array(pointsarray.keys)     var sortedkeys = sort(myarr) {     var obj1 = dict[$0] // ob associated w/ key 1     var obj2 = dict[$1] // ob associated w/ key 2     return obj1 > obj2            } 

this gives me

value of type [ dictionary <string,int>] has no member keys. 

i guess that's cause i'm trying run sort on array of dicts vs dicts themselves? how switch actual dictionaries vs. running sort on array?

right - you're not accessing keys of dictionaries.

here's working code:

var pointsarray = [dictionary<string, int>]()  pointsarray.append(["1" : 10]) pointsarray.append(["2" : 45]) pointsarray.append(["3" : 30])  // sort points let sorted = pointsarray.sort({ $0.first!.1 > $1.first!.1 })  print(sorted) // [["2": 45], ["3": 30], ["1": 10]] 

array(pointsarray.keys) - doesn't work, because pointsarray array, therefore doesn't have keys property. contents of pointsarray dictionaries , have keys. can access keys of first dictionary this: pointsarray[0].keys


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -