swift - 您如何利用 Swift 特性来重构这个递归函数?

标签 swift recursion nsdictionary

我一直在研究递归函数,以从表示为 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/

相关文章:

java - if-else 语句内的递归调用

c# - Recursive Hierarchy - 使用 Linq 的递归查询

swift - swift : Firebase DB/Dictionary look for highest Int

android - 如何在 Android 中从数组和映射创建 JSON?

objective-c - 尝试将 NSDictionary 从 swift 类传递到 objective-c 类时,无法识别的选择器发送到实例

ios - 单元格不快速显示 subview

swift Realm : Can't update subset of object with primary key

c# - 加起来等于给定自然数的总和组合

swift - UITableViewCell 中的 UIImageView 仅在滚动到视野之外后才出现?

swift - 从 Swift 5 中的 firebase 实时数据库返回一个 int