Wayne Filkins Wayne Filkins - 2 months ago 6
Swift Question

How do I sort an NSDictionary by integer value?

I have a

NSDictionary
. When I print it, it looks like this:

{
3gZ0qtk0yMUEvtSmz2RW40Y7AC83 = 12;
USXhV0QYkpbSzAmXgfeteXHuoqg2 = 25;
UTPFBV5Q5IgTh17060c6WxNDQCO2 = 1;
fqsspZtskWVheqUQQtROepixsGB2 = 256;
}


I want to sort it so that it looks like this:

{
fqsspZtskWVheqUQQtROepixsGB2 = 256;
USXhV0QYkpbSzAmXgfeteXHuoqg2 = 25;
3gZ0qtk0yMUEvtSmz2RW40Y7AC83 = 12;
UTPFBV5Q5IgTh17060c6WxNDQCO2 = 1;
}


All of the methods I see needs a key name but I don't understand that. There is no key name. Sorry if this is duplicate but everything I try from other questions doesn't work. There's just too many ways out there and I get all kinds of errors and other problems so I want to know the best (latest), and most efficient way to sort
NSDictionaries
in this way.

Also it's coming from a firebase snapshot
example:

self.friendsDict = snapshot.value as! NSDictionary

Answer

try this -

let dict:NSMutableDictionary = [
    "3gZ0qtk0yMUEvtSmz2RW40Y7AC83" : 12,
    "USXhV0QYkpbSzAmXgfeteXHuoqg2" : 25,
    "UTPFBV5Q5IgTh17060c6WxNDQCO2" : 1,
    "fqsspZtskWVheqUQQtROepixsGB2" : 256
]

let sortedKeys2 = (dict as NSDictionary).keysSortedByValueUsingComparator
    {
       ($1 as! NSNumber).compare($0 as! NSNumber)
}

OR

let dict = [
"3gZ0qtk0yMUEvtSmz2RW40Y7AC83" : 12,
"USXhV0QYkpbSzAmXgfeteXHuoqg2" : 25,
"UTPFBV5Q5IgTh17060c6WxNDQCO2" : 1,
"fqsspZtskWVheqUQQtROepixsGB2" : 256

]

var sortedKeys = Array(dict.keys).sort({dict[$0] > dict[$1]})
Comments