【问题标题】:Why does "for (index, (a, b)) in dict.enumerated()" produce an error?为什么“for (index, (a, b)) in dict.enumerated()”会产生错误?
【发布时间】:2017-02-08 16:04:52
【问题描述】:

我试图遍历字典:

let someDict = [...]
for (index, (a, b)) in someDict.enumerated() {

}

它显示了一个错误:

不能表示元组转换'(offset: Int, element: (key: String, value: String))'到'(Int, (String, String))'

这真的很奇怪。因为如果我们比较所需的元组:

(offset: Int, element: (key: String, value: String))

在for循环中使用元组类型:

(Int, (String, String))

它们是兼容的!

为什么会这样?

注意,我知道字典没有特定的顺序,因此知道 KVP 的索引不是很有用。但我仍然想知道为什么这不起作用。

【问题讨论】:

  • 我不知道为什么,但for (index, (key: a, value: b)) in someDict.enumerated() 有效。
  • 这可能与SR-922 有关,其中类型检查器有时无法匹配相同类型但不同标签的元组。
  • @Hamish 但是如果我使用像[Double: String] 这样的字典,它仍然无法编译!
  • @Sweeper 不太清楚你的意思。请原谅我只是很密集,但您已经在您的示例中使用了字典 - 为什么将键更改为 Double 类型允许它编译?
  • @Hamish 你说这与类型检查器无法匹配相同类型的元组有关。但事实并非如此,因为如果是这样,如果我将字典更改为 [Double: String],它就会起作用。

标签: swift for-loop dictionary swift3


【解决方案1】:

来自The Swift Programming Language (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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2018-11-29
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多