Why does “for (index, (a, b)) in dict.enumerated()” produce an error?

南笙酒味 提交于 2019-12-22 18:44:14

问题


I tried to loop through a dictionary:

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

}

It shows me an error:

cannot express tuple conversion '(offset: Int, element: (key: String, value: String))' to '(Int, (String, String))'

This is really weird. Because if we compare the required tuple:

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

with the tuple type in the for loop:

(Int, (String, String))

They are compatible!

Why is this happening?

Note, I understand that dictionaries don't have a specific order, hence knowing the index of the KVP is not very useful. But I still want to know why this doesn't work.


回答1:


From The Swift Programming Language (Swift 3) "When an element of a tuple type has a name, that name is part of the type."

I found relying on type inference like so:

  let someDict = [...]
  for tuple in someDict.enumerated() {
    let index = tuple.offset
    let a = tuple.element.key
    let b = tuple.element.value

  }

avoids having to explicitly type the tuple

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


来源:https://stackoverflow.com/questions/39785389/why-does-for-index-a-b-in-dict-enumerated-produce-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!