Swift - what determines the order of a collection of dictionaries?

When I say order - I mean the order that the compiler chooses to display the results, I know that the dictionary does not have an index, such as an array.

I have the following dictionary:

let groups :Dictionary<String,AnyObject> = [ "Data": ["Save", "Restore"], "Load Tabs": ["Reload Tabs when selecting tab"], "Privacy": ["Set Passcode"], "About Me": ["Twitter", "LinkedIn"]] 

But the console shows that it is displayed as follows:

["Privacy": ("Set Password"), "Download Tabs": ("Reload Tabs When You Select Tabs"), "Data": (Save, Restore), "About Me": (Twitter, LinkedIn)]

As you can see, the order is different, but when I change the order of the dictionary code, the output remains the same.

So can someone clarify this for me, please, so that I better understand how this is achieved? I am not trying to manipulate the dictionary, but I am trying to understand how the output is determined.

If the keys do not have a given order, should they not appear randomly every time the dictionary gives a result?

+5
source share
1 answer

Dictionary work with Hashable keys and are implemented using a hash table , a commonly used way to represent associative arrays using O(1) lookups. The hash tables are usually sorted by the integer value of the hash code for small numbers of key-value pairs (below the threshold of the bucket), and after that - in the reverse order of entry. This means that you cannot rely on hash tables that should be sorted in any reasonable or predictable order in most cases.

+8
source

Source: https://habr.com/ru/post/1235966/


All Articles