我引入了一些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"
}
}
}
}
你会如何迭代声音?
答案 0 :(得分:0)
我为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 {
// ...
}