我一直在研究一個遞歸函數來提取表示爲NSDictionary的JSON數據中的字符串值。該功能可讓您做到這一點:如何利用Swift特性來重構這個遞歸函數?
if let value = extractFromNestedDictionary(["fee" : ["fi" : ["fo" : "fum"]]], withKeys: ["fee", "fi", "fo"]) {
println("\(value) is the value after traversing fee-fi-fo");
}
,函數執行如下:
// Recursively retrieves the nested dictionaries for each key in `keys`,
// until the value for the last key is retrieved, which is returned as a String?
func extractFromNestedDictionary(dictionary: NSDictionary, withKeys keys: [String]) -> String? {
if keys.isEmpty { return nil }
let head = keys[0]
if let result: AnyObject = dictionary[head] {
if keys.count == 1 {
return result as? String
} else {
let tail: [String] = Array(keys[1..<keys.count])
if let result = result as? NSDictionary {
return extractFromNestedDictionary(result, withKeys: tail)
} else {
return nil
}
}
} else {
return nil
}
}
是否有雨燕1.2/2.x中,可以結合有關可選擇一些語法特點:
- 使該功能更加簡潔
- 少用
if
築巢
這個問題看起來像一個很好的候選人http://codereview.stackexchange.com。 –
感謝@MartinR,我不知道那個堆棧交換筒倉。 – ybakos