如何访问Swift字典中的下一个键? [英] How to access the next key in a Swift dictionary?

查看:153
本文介绍了如何访问Swift字典中的下一个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

for (k, v) in myDict {
    println(k)
}

如何访问字典中的下一个键(例如myDict [k + 1] )

How do I access the next key in the dictionary (e.g. myDict[k + 1])?

提前感谢

推荐答案

作为下一个关键的东西;字典没有命令。

There is no such thing as "the next key"; dictionaries have no order.

然而,您正在遍历字典...

Since, however, you are iterating through the dictionary...

for (k, v) in myDict {
    println(k)
}

我要假设你的意思是:我怎么知道,在这个迭代,什么 k 将在下一个迭代?

I'm going to assume that what you mean is: how can I know, on this iteration, what k would be on the next iteration?

一个简单的解决方案是将字典强制为数组(键值元组):

A simple solution would be to coerce the dictionary to an array (of key-value tuples):

let arr = Array(myDict)

现在你有整数索引的东西。所以你可以这样枚举:

Now you have something with integer indexes. So you can enumerate it like this:

let arr = Array(myDict)
for (ix, (k,v)) in enumerate(arr) {
    println("This key is \(k)")
    if ix < arr.count-1 {
        println("The next key is \(arr[ix+1].0)")
    }
}






当然,事实是,你可以枚举一个字典直接,但索引不是整数,所以它们有点难以使用。马丁·R也正在展现一种说明这一点的方法。


The truth is, of course, that you can enumerate a dictionary directly, but indexes are not integers, so they are a little harder to work with. Martin R is also showing an approach illustrating that point.

这篇关于如何访问Swift字典中的下一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆