繁体   English   中英

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

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

我有一本字典,我想循环它并获取键、值和它的索引为Int ,但是在我的循环中,我只是获取键和值,我怎样才能获取索引?

这是我获取其键和值的代码:

var myDict:[String: String]?

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

我的预期结果是也打印索引print(key, value, index)

字典是无序的,所以你所能做的就是枚举字典,像这样:

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