Swift’s Dictionary
is a hash-based data structure. Unless a specific ordering mechanism is in place, the order of items in hash-based structures depends on several factors:
- Hash values of objects used as keys –
hashValue
method is used to determine the bucket number for the item - Size of the structure – Since
hashValue
can be much larger than the number of buckets available, a limiting mechanism, such as modulo bucket count, is used to decide the actual bucket number - Modification order – this becomes relevant when keys have collisions. Elements with duplicate hash value placed later would either go to a different bucket, or be placed in a list associated with the actual bucket.
For example, if you change the size of dictionary in your second example, the order of items would reverse:
var test1 = [String:String]() // Use default initial capacity
test1["Tomorrow"] = "Bla"
test1["One Month"] = "Bla"
print(test1) // ["One Month": "Bla", "Tomorrow": "Bla"]
var test2 = [String:String](minimumCapacity: 11) // Use specific capacity
test2["Tomorrow"] = "Bla"
test2["One Month"] = "Bla"
print(test2) // ["Tomorrow": "Bla", "One Month": "Bla"]
Since some of these parameters are outside your control, the order of items in a Dictionary
can be considered arbitrary for all practical purposes.
1
solved Are Swift dictionaries automatically sorted?