我一直在研究递归函数,以从表示为 NSDictionary 的 JSON 数据中提取字符串值。该函数允许您执行此操作:
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 中是否有一些与可选绑定(bind)相关的语法特性可以:
- 让这个功能更简洁
- 少用
if
嵌套
最佳答案
您可以在 keys
数组上使用 reduce
而不是递归
遍历字典:
func extractFromNestedDictionary(dictionary: NSDictionary, withKeys keys: [String]) -> String? {
return reduce(keys, dictionary as AnyObject?) {
($0 as? NSDictionary)?[$1]
} as? String
}
在闭包内部,$0
是当前级别的(可选)对象,$1
当前 key 。闭包返回下一层的对象
如果 $0
是一个字典并且具有当前键的值,
和 nil
否则。 reduce()
的返回值是
最后一层的对象或 nil
。
关于swift - 您如何利用 Swift 特性来重构这个递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31360898/