Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all keys of nsdictionary sorted alphabetically in swift?

I have got a NSDictionary with alphabets as keys. I want to get those keys sorted alphabetically . I have tried many methods but I am getting error on Sort() method. Can any one help me ????

Thanks in advance

Note: 1) I don't want to get a sorted array of dictionaries 2) I don't want to sort the dictionary by means of the values (I am getting a lot of answers for this )

like image 260
Karan Alangat Avatar asked Nov 28 '22 14:11

Karan Alangat


1 Answers

You can sort the keys this way:

let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(<) // ["a", "b"]

Swift 3:

let dictionary: NSDictionary = ["a" : 1, "b" : 2]
let sortedKeys = (dictionary.allKeys as! [String]).sorted(by: <) // ["a", "b"]
like image 150
Kirsteins Avatar answered Dec 05 '22 13:12

Kirsteins