目前尚不清楚您尝试了什么以及卡在哪里,您确实应该将其包括在内 - 不这样做将是您被否决的原因。
但是,让我们看看我们是否可以提供帮助。您声明您的字典是[String:Any] 类型并且没有给出任何嵌套限制,所以我们将使用以下测试数据:
let sampleDict : [String:Any] =
[
"foo": [ "bar": "tralala" ],
"test": [ "foo": "bar", "staging": "hi"],
"staging" : 3,
"one" : [ "two" : [ "three" : 3, "staging" : 4.2]],
"aaa": [ "bbb": "cccc", "staging": "jjj"]
]
如果我们的算法能够应对它,它应该能够应对任何事情(著名的遗言......)。
使用预定义方法并避免循环的简单算法:
- 过滤字典,删除需要删除键的任何键/值对。
- 映射过滤字典中的值,对于任何本身是
[String:Any] 字典的值,递归地将此算法应用于该值。
在 Swift 中:
func removeMatchingKeys(_ dict : [String:Any], _ keysToRemove : [String]) -> [String:Any]
{
return dict
// filter keeping only those key/value pairs
// where the key isn't in keysToRemove
.filter { !keysToRemove.contains($0.key) }
// map the values in the filtered dictionary recursing
// if the value is itself a [String:Any] dictionary
.mapValues
{ if let nested = $0 as? [String:Any]
// value is dictionary, recurse
{ return removeMatchingKeys(nested, keysToRemove) }
else
// value isn't a dictionary, leave as is
{ return $0 }
}
}
用按键测试:
let sampleKeys = ["test", "staging"]
声明:
print( removeMatchingKeys(sampleDict, sampleKeys) )
生产:
["foo": ["bar": "tralala"], "aaa": ["bbb": "cccc"], "one": ["two": ["three": 3.0]]]
上述算法对数据进行两次传递,首先对其进行过滤,然后对其进行映射。如果,且仅当,结果证明这是一个性能问题,您可以将两个预定义函数 filter 和 map 替换为一个简单的手写循环,该循环结合了这些操作并且只通过数据一次。
注意:以上使用 Xcode 10/Swift 4.2,使用任何其他版本和 YMMV(即语法和预定义函数可能很容易不同)但算法仍然适用。