Swift 遍历字典

Swift step through dictionary

我想知道 Swift 中是否有单步执行字典的方法。我知道我可以遍历,但我希望在用户点击 "next" 按钮时逐步浏览项目字典。

我想我可以先遍历字典并将键存储在一个数组中,然后遍历键并根据需要检索每个项目,因为数组可以被索引。不过,这似乎有点不雅。有什么想法吗?

我目前的做法:

var iterator = 0
var keys = [String]()

func loadKeys() {
    for (key, value) in items {
        keys.append(key)
    }
}

func step() {
    iterator += 1
    let currentKey = keys[iterator]
    let currentItem = items[currentKey]
}

我认为它会工作得很好,只是不确定这是最佳做法。

感谢您的帮助!

字典是一个索引集合,因此您可以使用字典的索引逐步遍历键和值:

var i = items.startIndex

func step() {
    guard i != items.endIndex else {
        // at the end of the dictionary
        return
    }

    let (currentKey, currentValue) = items[i]
    i = items.index(after: i)
}

字典还为您提供了一个迭代器,因此您可以使用它逐步执行它:

var iterator = items.makeIterator()

func step() {
  if let v = iterator.next() {
     let currentKey = v.key
     let currentValue = v.value
  } 
}