swiftsortingdictionary

Sort Dictionary by keys


I want to sort a dictionary in Swift. I have a dictionary like:

"A" => Array[]
"Z" => Array[]
"D" => Array[]

etc. I want it to be like

"A" => Array[]
"D" => Array[]
"Z" => Array[]

etc.

I have tried many solutions on SO but no one worked for me. I am using XCode6 Beta 5 and on it some are giving compiler error and some solutions are giving exceptions. So anyone who can post the working copy of dictionary sorting.


Solution

  • let dictionary = [
        "A" : [1, 2],
        "Z" : [3, 4],
        "D" : [5, 6]
    ]
    
    let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]
    

    EDIT:

    The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary' is also a 'CollectionType' of (key, value) pairs and we can use the global 'sorted' function to get a sorted array containg both keys and values, like this:

    let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
    print(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]
    

    EDIT2: The monthly changing Swift syntax currently prefers

    let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]
    

    The global sorted is deprecated.