简体   繁体   中英

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?

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)

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) }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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