我试图遍历字典:
let someDict = [...]
for (index, (a, b)) in someDict.enumerated() {
}
它显示了一个错误:
cannot express tuple conversion '(offset: Int, element: (key: String, value: String))' to '(Int, (String, String))'
这真的很奇怪。因为如果我们比较所需的元组:
(offset: Int, element: (key: String, value: String))
在 for 循环中使用元组类型:
(Int, (String, String))
它们是兼容的!
为什么会这样?
注意,我知道字典没有特定的顺序,因此知道 KVP 的索引不是很有用。但我仍然想知道为什么这不起作用。
最佳答案
来自Swift 编程语言(Swift 3)
"When an element of a tuple type has a name, that name is part of the type."
我发现像这样依赖类型推断:
let someDict = [...]
for tuple in someDict.enumerated() {
let index = tuple.offset
let a = tuple.element.key
let b = tuple.element.value
}
避免必须显式键入元组
var tuple: (offset: Int, element: (key: String, value: String))
关于swift - 为什么 "for (index, (a, b)) in dict.enumerated()"会产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785389/