我一直在研究一个递归函数,以从表示为NSDictionary的JSON数据中提取String值。该函数允许您执行以下操作:
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
}
}
Swift 1.2 / 2.x中是否存在与可选绑定相关的一些语法功能,这些功能可以:
if
嵌套除了递归,您还可以reduce
在keys
数组上使用来遍历字典:
func extractFromNestedDictionary(dictionary: NSDictionary, withKeys keys: [String]) -> String? {
return reduce(keys, dictionary as AnyObject?) {
($0 as? NSDictionary)?[$1]
} as? String
}
在闭包内部,$0
是当前级别和$1
当前键上的(可选)对象。如果$0
是字典并且具有当前键的值,则闭包将在下一级返回对象,nil
否则返回。reduce()
那么从的返回值就是最后一级或上的对象nil
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句