2015-10-17 21 views
-1

我已經引入了一些JSON,將它轉換爲字典,並想知道是否有一種有效的方法來遍歷它的特定級別(嵌套)如何遍歷Swift中字典的特定部分?

例如,從以下:

{ 
    "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

這應該讓你開始http://stackoverflow.com/問題/ 24111627 /迭代通-A-字典功能於迅速 –

回答

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 { 
    // ... 
}