Get all keys of nsdictionary sorted alphabetically in swift?

12,871

Solution 1

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"]

Solution 2

In Swift 2.2

You can sort like this in Ascending Order

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

Descending Order

let myDictionary: Dictionary = ["a" : 1, "b" : 2]
let sortedKeys = myDictionary.keys.sort(>)        // ["b", "a"]
Share:
12,871
Karan Alangat
Author by

Karan Alangat

iOS Developer

Updated on June 04, 2022

Comments

  • Karan Alangat
    Karan Alangat almost 2 years

    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 )