简体   繁体   English

如何在字典循环中获取键、值和索引?

[英]How to get the key, value and index in a Dictionary loop?

I have a dictionary and I want to loop it and get the key, value and it's index as Int , but with my loop, I'm just only getting the key and value, how can I get the index?我有一本字典,我想循环它并获取键、值和它的索引为Int ,但是在我的循环中,我只是获取键和值,我怎样才能获取索引?

This is my code for getting its key and value:这是我获取其键和值的代码:

var myDict:[String: String]?

func getKeyValueIndex() {
    if let myDict = myDict {
        for (key, value) in myDict { print(key, value) }
    }
}

My expected result was to print the index too print(key, value, index)我的预期结果是也打印索引print(key, value, index)

Dictionaries are unordered, so all you can do is to enumerate through the dictionary, like this:字典是无序的,所以你所能做的就是枚举字典,像这样:

func getKeyValueIndex() {
    if let myDict = myDict {
        for (index, dict) in myDict.enumerated() { print(index, dict.key, dict.value) }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM