问题
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