【问题标题】:How do you iterate through a specific part of a dictionary in Swift?如何在 Swift 中遍历字典的特定部分?
【发布时间】:2016-01-16 11:09:48
【问题描述】:

我引入了一些 JSON,将其转换为字典,并想知道是否有有效的方法来迭代它的特定级别(嵌套是什么)

例如,从以下开始:

{
    "instrument": {
        "piano": {
            "sounds": {
                "C": "pianoC.mp3",
                "D": "pianoD.mp3",
                "E": "pianoE.mp3",
                "F": "pianoF.mp3",
                "G": "pianoG.mp3",
                "A": "pianoA.mp3",
                "B": "pianoB.mp3",
                "C8": "pianoC8.mp3"
             }
         },
         "guitar": {
             "sounds": {
                 "CMajor": "guitarCMajor.mp3”,
                 "FMajor": "guitarDMajor.mp3",
                 "GMajor": "guitarGMajor.mp3",
                 "AMinor": "guitarAMinor.mp3"
             }
         }
    }
}

你将如何迭代声音?

【问题讨论】:

标签: json swift dictionary nested iteration


【解决方案1】:

我给Dictionary写了一些扩展:

extension Dictionary {
    func filterValues<T>() -> [T] {
        return values.filter { $0 is T }.map { $0 as! T }
    }

    func filterDictionaries() -> [Dictionary] {
        return filterValues()
    }

    func valuesOfLevel<T>(level: Int) -> [T] {
        var levelItems = [self]
        for _ in 0..<level-1 {
            levelItems = levelItems.flatMap { $0.filterDictionaries() }
        }
        return levelItems.flatMap { $0.filterValues() }
    }

    func dictionariesOfLevel(level: Int) -> [Dictionary] {
        return valuesOfLevel(level)
    }

    func dictionariesOfLevel(level: Int, key: Key) -> [Dictionary] {
        return dictionariesOfLevel(level)
            .flatMap { ($0[key] as? Dictionary) ?? [:] }
            .filter { !$0.isEmpty }
    }

    func valuesOfLevel<T>(level: Int, key: Key) -> [T] {
        return dictionariesOfLevel(level, key: key)
            .flatMap { $0.values }
            .filter { $0 is T }
            .map { $0 as! T }
    }
}

在您的情况下,您可以过滤声音并通过以下方式遍历它们:

let sounds: [String] = dictionary.valuesOfLevel(2, key: "sounds")

for sound in sounds {
  // ...
}

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2014-07-29
    • 2016-10-25
    • 2021-01-10
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多