swift - 为什么 "for (index, (a, b)) in dict.enumerated()"会产生错误?

标签 swift for-loop dictionary swift3

我试图遍历字典:

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/

相关文章:

swift - 如何以正确的顺序执行乘法和/或除法?

swift - 如何在 Xcode 7.2 XCTestCase 中获取 ScrollView 的标签?

java - HashMap put 还是 putAll? - java

python - 用于字数缓存的嵌套字典

swift - ARKIT 无法在渲染方法中缩放或旋转

swift - 如何以编程方式更新 UIView 的恒定高度约束?

python - 为什么 for 循环和 np.random.shuffle 在 Python 中不能按预期工作?

java - 如何遍历 Java 中函数返回的数组

python - pandas - 使用 for 循环将多列附加到数据框

python - 带迭代的二维字典