Enumerating dictionary in Swift

Jay*_*mar 8 dictionary enumeration 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)")
}
Run Code Online (Sandbox Code Playgroud)

should be:

Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
Run Code Online (Sandbox Code Playgroud)

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")
Run Code Online (Sandbox Code Playgroud)

Can anyone please explain this behavior?

vad*_*ian 17

不是错误,您造成了混乱,因为您使用了错误的 API。

您可以使用此(与字典相关的)语法获得预期结果

for (key, value) in someDict { ...
Run Code Online (Sandbox Code Playgroud)

在哪里

  • key 是字典键
  • value 是字典值。

使用(数组相关)语法

for (key, value) in someDict.enumerated() { ...
Run Code Online (Sandbox Code Playgroud)

这实际上是

for (index, element) in someDict.enumerated() { ...
Run Code Online (Sandbox Code Playgroud)

字典被视为一个元组数组,并且

  • key索引
  • value是一个元组 ("key": <dictionary key>, "value": <dictionary value>)