Swift 4:以递归方式在嵌套的动态Dictionary <string,any =“”>中查找值

时间:2018-02-02 13:05:18

标签: swift dictionary recursion closures

在给定的词典中,我需要为给定的键找到嵌套的词典([String : Any])。

字典的一般结构(例如嵌套级别,值类型)是未知的并且是动态给出的。 [1]

在这个子词典里面,有一个给定的值&#34;值&#34; (不要问)需要提取哪些内容。

以下是一个例子:

let theDictionary: [String : Any] =
  [ "rootKey" :
    [ "child1Key" : "child1Value",
      "child2Key" : "child2Value",
      "child3Key" :
        [ "child3SubChild1Key" : "child3SubChild1Value",
          "child3SubChild2Key" :
              [ "comment" : "child3SubChild2Comment", 
                 "value" : "child3SubChild2Value" ]
        ],
      "child4Key" :
        [ "child4SubChild1Key" : "child4SubChild1Value",
          "child4SubChild2Key" : "child4SubChild2Value",
          "child4SubChild3Key" :
            [ "child4SubChild3SubChild1Key" :
                [ "value" : "child4SubChild3SubChild1Value", 
                  "comment" : "child4SubChild3SubChild1Comment" ]
            ]
        ]
    ]
  ]

使用强力和伪记忆,我设法破解了一个函数,它遍历整个Dictionary并获取给定键的值:

func dictionaryFind(_ needle: String, searchDictionary: Dictionary<String, Any>) -> String? {

  var theNeedleDictionary = Dictionary<String, Any>()

    func recurseDictionary(_ needle: String, theDictionary: Dictionary<String, Any>) -> Dictionary<String, Any> {
      var returnValue = Dictionary<String, Any>()
      for (key, value) in theDictionary {
        if value is Dictionary<String, Any> {
          if key == needle {
            returnValue = value as! Dictionary<String, Any>
            theNeedleDictionary = returnValue
            break
          } else {
              returnValue =  recurseDictionary(needle, theDictionary: value as! Dictionary<String, Any>)
            }
        }
     }
     return returnValue
    }
  // Result not used
  _ = recurseDictionary(needle, theDictionary: searchDictionary)

  if let value = theNeedleDictionary["value"] as? String {
    return value
  }
  return nil
}

到目前为止这是有效的。 (为了您的游乐场测试乐趣:

let theResult1 = dictionaryFind("child3SubChild2Key", searchDictionary: theDictionary)
print("And the result for child3SubChild2Key is: \(String(describing: theResult1!))")

let theResult2 = dictionaryFind("child4SubChild3SubChild1Key", searchDictionary: theDictionary)
print("And the result for child4SubChild3SubChild1Key is: \(String(describing: theResult2!))")

let theResult3 = dictionaryFind("child4Key", searchDictionary: theDictionary)
print("And the result for child4Key is: \(String(describing: theResult3))")

)。

我的问题在这里:

什么是更干净,简洁,更快速的方式来迭代字典,特别是 - 一旦找到所需的密钥,就完全脱离例程?

甚至可以使用字典扩展来实现解决方案吗?

全部谢谢!

[1] Remove nested key from dictionary中描述的KeyPath不可行。

2 个答案:

答案 0 :(得分:5)

更紧凑的递归解决方案可能是:

func search(key:String, in dict:[String:Any], completion:((Any) -> ())) {
    if let foundValue = dict[key] {
        completion(foundValue)
    } else {
        dict.values.enumerated().forEach {
            if let innerDict = $0.element as? [String:Any] {
                search(key: key, in: innerDict, completion: completion)
            }
        }
    }
}

用法是:

search(key: "child3SubChild2Key", in: theDictionary, completion: { print($0) }) 

给出:

["comment": "child3SubChild2Comment", "value": "child3SubChild2Subchild1Value"]

或者,如果您不想使用闭包,可以使用以下内容:

extension Dictionary {
    func search(key:String, in dict:[String:Any] = [:]) -> Any? {
        guard var currDict = self as? [String : Any]  else { return nil }
        currDict = !dict.isEmpty ? dict : currDict

        if let foundValue = currDict[key] {
            return foundValue
        } else {
            for val in currDict.values {
                if let innerDict = val as? [String:Any], let result = search(key: key, in: innerDict) {
                    return result
                }
            }
            return nil
        }
    }
}

用法是:

let result = theDictionary.search(key: "child4SubChild3SubChild1Key")
print(result) // ["comment": "child4SubChild3SubChild1Comment", "value": "child4SubChild3SubChild1Value"]

答案 1 :(得分:0)

以下扩展可用于在嵌套字典中查找键的值,其中不同的级别可以包含与不同值关联的相同键。

extension Dictionary where Key==String {
    func find<T>(_ key: String) -> [T] {
        var keys: [T] = []
        
        if let value = self[key] as? T {
            keys.append(value)
        }
        self.values.compactMap({ $0 as? [String:Any] }).forEach({
            keys.append(contentsOf: $0.find(key))
        })
        
        return keys
    }
}