枚举 Swift 中的字典
Enumerating dictionary in Swift
我想我注意到 Swift 字典枚举实现中的错误。
此代码片段的输出:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
应该是:
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
而不是:
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")
谁能解释一下这种行为?
这 不是 错误,您造成混乱是因为您使用了错误的 API。
您使用此(字典相关)语法
得到了预期的结果
for (key, value) in someDict { ...
哪里
key
是字典键
value
是字典值。
使用(数组相关)语法
for (key, value) in someDict.enumerated() { ...
实际上是
for (index, element) in someDict.enumerated() { ...
字典被视为元组数组,并且
key
是 index
value
是一个 元组 ("key": <dictionary key>, "value": <dictionary value>)
我想我注意到 Swift 字典枚举实现中的错误。
此代码片段的输出:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
应该是:
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
而不是:
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")
谁能解释一下这种行为?
这 不是 错误,您造成混乱是因为您使用了错误的 API。
您使用此(字典相关)语法
得到了预期的结果for (key, value) in someDict { ...
哪里
key
是字典键value
是字典值。
使用(数组相关)语法
for (key, value) in someDict.enumerated() { ...
实际上是
for (index, element) in someDict.enumerated() { ...
字典被视为元组数组,并且
key
是 indexvalue
是一个 元组("key": <dictionary key>, "value": <dictionary value>)