1

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 {
    print(i)
}

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?

Daniel
  • 20,420
  • 10
  • 92
  • 149
Brandon Bradley
  • 3,160
  • 4
  • 22
  • 39

2 Answers2

5

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])")
}
Daniel
  • 20,420
  • 10
  • 92
  • 149
  • This will print a ordered result, but if try to re-assign a new dic with this result ordered, it will maintain unordered – Daniel Arantes Loverde Apr 23 '18 at 21:39
  • As written in the answer, dictionaries are not ordered, you must convert them or iterate over the keys/values to get a sorted result – Daniel Apr 23 '18 at 22:05
1

A dictionary (Swift or NSDictionary) is a key-value map. There is no order by concept. You put in one value (key) and get out another value (value) for that key. This does not depend on any order.

If you want to have an order of keys, get the keys and sort them.

BTW: There is a difference between ordered and sorted. Ordered means, that an element keeps it place. This order can be unsorted, whatever sorting means.

To show the difference think of a dictionary creation like this:

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

If a dictionary would be ordered, the result of your code would be: b, a, c, d. This is the order the dictionary was created. But it is not sorted. (Sort how? Phonetic? Literally? Alphanumeric?)

Arrays, which are ordered (aka keeps the place of an element) are not sorted, too. Having a homogene ordered collection as NSArray an order is kept, even if there is no way to sort them: Think of an array which contains strings, numbers and images. The array keeps the order you put the items in. But it has no idea to sort it. (Again: Whatever sorting means.) In the whole biosphere of Swift, Objective-C, and Foundation there is only one sorted collection: NSIndexSet.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50