Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - what determines the order of a Dictionary Collection?

When I say order - I mean the order that the compiler chooses to display the results, I know that a dictionary has no index like an array does.

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 it displayed like this:

["Privacy": ( "Set Passcode" ), "Load Tabs": ( "Reload Tabs when selecting tab" ), "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 is still the same.

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

If keys don't have a set order, should it not appear random each time the dictionary gives an output?

like image 709
jwknz Avatar asked Nov 14 '15 21:11

jwknz


Video Answer


1 Answers

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

like image 147
Clashsoft Avatar answered Oct 17 '22 00:10

Clashsoft