检查一个词典是否是另一个词典的子级

时间:2019-07-08 14:56:36

标签: swift dictionary

我正在尝试比较两个字典,如果trueleft dictionary的子代(内部),则该函数将返回right dictionary,否则返回false。字典的类型为[String: Any]

我一直在寻找解决方案,但是我发现了一个相等的函数,如下所示:

NSDictionary(dictionary: lhs).isEqual(to: rhs)

谢谢您的建议

1 个答案:

答案 0 :(得分:0)

我找到了一种方法,但是它是一维的。这意味着它将在给定的字典值中搜索字典。我认为您可以将其设为递归。

extension NSDictionary {
    func contains(dict: NSDictionary) -> Bool {

         return self.contains { (selfKeyValue) -> Bool in
            if let foundDict = (selfKeyValue.value as? NSDictionary), let anyDict = dict as? [AnyHashable : Any]  {
                return foundDict.isEqual(to: anyDict)
            }

            return false
        }
    }
}



let dict1 = ["bb":123]
let dict2 = ["a": ["aa": 123],"b": ["bb":123]]



print((dict2 as NSDictionary).contains(dict: dict1 as NSDictionary))

输出:true