Get all keys from nsdictionary sorted alphabetically in fast?

I have an NSDictionary with alphabets as keys. I want these keys sorted alphabetically. I tried many methods, but I get an error in the Sort () method. Can someone help me ????

Thanks in advance

Note: 1) I do not want to get a sorted array of dictionaries 2) I do not want to sort a dictionary using values ​​(I get a lot of answers for this)

+4
source share
3 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"] 
+18
source

In Swift 2.2

You can sort it in ascending order.

 let myDictionary: Dictionary = ["a" : 1, "b" : 2] let sortedKeys = myDictionary.keys.sort() // ["a", "b"] 

Descending

 let myDictionary: Dictionary = ["a" : 1, "b" : 2] let sortedKeys = myDictionary.keys.sort(>) // ["b", "a"] 
+3
source

For Swift 3

  // Initialize the Dictionary let dict = ["name": "John", "surname": "Doe"] // Get array of keys var keys = Array(dict.keys).sorted(by: >) print(keys) 
0
source

All Articles