Dictionary (key, value)

Suppose I have the following code

var dictionary = ["cat": 2,"dog":4,"snake":8]; // mutable dictionary var keys = dictionary.keys var values = dictionary.values for e in keys { println(e) } for v in values { println(v) } 

Dictionary .keys and dictionary.values ​​are in the same order

for example, if the .keys dictionary is "dog", "snake", "cat", will the value of the dictionary always be 4,8,2? I tried this on the playground, and the result always indicated that they are in the same order

0
source share
2 answers

No, this is not guaranteed in the same order. From the documentation:

The Swifts dictionary type is an unordered collection. The order in which keys, values, and key-value pairs are retrieved during iteration through a dictionary is not specified.

+4
source

The definition of the keys and values properties is preceded by the following: comments:

 /// A collection containing just the keys of `self` /// /// Keys appear in the same order as they occur as the `.0` member /// of key-value pairs in `self`. Each key in the result has a /// unique value. var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> { get } /// A collection containing just the values of `self` /// /// Values appear in the same order as they occur as the `.1` member /// of key-value pairs in `self`. var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> { get } 

My interpretation

Keys / Values ​​are displayed in the same order that they occur as a member of a .0 / .1 key-value pair in self .

it is that dictionary.keys and dictionary.values return the keys and values ​​in an β€œappropriate” order.

Thus, the key-value pairs of the dictionary do not have a specific order, but the first, second, ... dictionary.values element is the dictionary.values value corresponding to the first, second, ... dictionary.keys element.

+1
source

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


All Articles