0

I am pulling data from Firebase and in every loop I will get one piece of data in NSDictionary format (e.g. 1st loop I get {Kelvin: 10} , 2nd loop I get {John, 40}, 3rd loop I get {Mary, 27} ,etc)

I created a variable called "namedic" to store the data

var namedic = [NSDictionary]()

I then use an if statement in the loop to catch the data

if let myname = thename["name:"] as? NSDictionary {

           //(thename["name:"] prints {Kelvin: 10}

         self.namedic.append(myname)
                        }

I will then get an array of NSDictionaries

[{
    "Kelvin" = 10;
 }, {
    "John" = 40;
   }, {
    "Mary" = 27;
}]

My question is, how do I sort this array of NSDictionaries in alphabetical order?

What I want is this:

[{
    "John" = 40;
 }, {
    "Kelvin" = 10;
    }, {
    "Mary" = 27;
}]
Xenos
  • 73
  • 2
  • 11
  • 1
    You are using keys which are supposed to be values. Consider a more suitable data structure for example `[["name" : "Kelvin", "amount" : 10], ["name" : "John" ...]]` – vadian May 16 '17 at 14:31
  • Possible duplicate of [Sort Dictionary by keys](http://stackoverflow.com/questions/25377177/sort-dictionary-by-keys) – l'L'l May 16 '17 at 14:31
  • `self.namedic.sort{return ($0 as [String:Any]).keys.first! < ($1 as [String:Any]).keys.first!}`? Or something similar with maybe better checks (I'm not a Swift developper). But the structure may be revisited. – Larme May 16 '17 at 14:32
  • Thanks. I think I will restructure the data instead. Much easier. – Xenos May 16 '17 at 14:39

0 Answers0