I guess I noticed a bug in the Swift Dictionary enumeration implementation.
The output of this code snippet:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
should be:
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
instead of:
Dictionary key 0 - Dictionary value (key: 2, value: "Two")
Dictionary key 1 - Dictionary value (key: 3, value: "Three")
Dictionary key 2 - Dictionary value (key: 1, value: "One")
Can anyone please explain this behavior?
The forEach() method is used to iterate through each element of a dictionary.
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. If you are familiar with C, you will know that C enumerations assign related names to a set of integer values.
There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.
Swift 4 dictionaries use unique identifier known as a key to store a value which later can be referenced and looked up through the same key. Unlike items in an array, items in a dictionary do not have a specified order. You can use a dictionary when you need to look up values based on their identifiers.
It's not a bug, you are causing the confusion because you are using the wrong API.
You get your expected result with this (dictionary related) syntax
for (key, value) in someDict { ...
where
key
is the dictionary key value
is the dictionary value.Using the (array related) syntax
for (key, value) in someDict.enumerated() { ...
which is actually
for (index, element) in someDict.enumerated() { ...
the dictionary is treated as an array of tuples and
key
is the index
value
is a tuple ("key": <dictionary key>, "value": <dictionary value>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With