Brandon Bradley Brandon Bradley - 2 months ago 7x
Swift Question

How Are Dictionary Keys Sorted In Swift?

Examine the following dictionary:

var testDict: [String : Int] = [
"a" : 1,
"b" : 2,
"c" : 3,
"d" : 4

Now, iterate through the keys of the dictionary:

for i in testDict.keys {

This generates the following output:

b a c d

However, the expected output would be the keys in the coded order:

a b c d

As this is not the case, I assume that the keys are sorted. If so, how are they sorted, and more importantly, how can they be returned to the order in which they were written?


From Apple's docs:

Unlike items in an array, items in a dictionary do not have a specified order

In short, dictionary items are not sorted, they are stored as efficiently as possible by their hashValue (you should not make any assumptions over the order), that's why:

A dictionary Key type must conform to the Hashable protocol, like a set’s value type.

To your second question, since a dictionary is not sorted, you cannot return the values or keys inside to the original order (since it didn't have any). What you can do is iterate through all values and keys in a specific order, like this:

let dic = ["a" : 1, "b" : 2, "c" : 3, "d" : 4]
for key in dic.keys.sort(<) {
    print("key: \(key), value: \(dic[key])")