Search code examples
swiftdictionaryenumeration

Enumerating dictionary in Swift


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?


Solution

  • 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>)