如何从 swift 字典数组中获取选定键数组的值及其复杂性

How to get the value of an array of selected keys from swift array of dictionaries and the complexity of it

假设我收到了以下回复。我想从以下操作中了解两件事。

1.) 如何 improve/optimise 下面的代码使用 swift 中的高阶函数。

2.) 还想知道代码的当前复杂度以及您可能建议的任何优化代码的复杂度。

在下面的响应中,我只想检查 keysToBeChecked 中描述的某些键的值,并且我需要为该特定键执行操作。操作完成后,我想向响应中添加一个新密钥 (key6),如下所示。以下操作对我来说很好,这就是我打算做的。我正在寻找上面提到的两件事

var response = [["key1": 1, "key2": 0, "name": "John", "key3": 1, "key4": 1, "place": "Newyork", "key5": 0],
                ["key1": 0, "key2": 1, "name": "Mike", "key3": 1, "key4": 0, "place": "California", "key5": 1],
                ["key1": 1, "key2": 0, "name": "John", "key3": 0, "key4": 1, "place": "Boston", "key5": 1]]
let keysToBeChecked = ["key1", "key2", "key3", "key4", "key5"]

for var item in response{
var dict = [String: String]()
   for(key, value) in item{
       if keysToBeChecked.contains(key){
           dict[key] = "\(value)"
           if dict[key] == "1"{
               //perform required operations
               output
           }
       }
   }

   item["key6"] = output
   response.append(item)
}
print(response)//should print the below


My expected output is

response = [["key1": 1, "key2": 0, "name": "John", "key3": 1, "key4": 1, "place": "Newyork", "key5": 0, "key6": "output"],
   ["key1": 0, "key2": 1, "name": "Mike", "key3": 1, "key4": 0, "place": "California", "key5": 1, "key6": "output"],
   ["key1": 1, "key2": 0, "name": "John", "key3": 0, "key4": 1, "place": "Boston", "key5": 1, "key6": "output"]]

对于高阶函数,你可以试试,

let result = response.map { (dict) -> [String:Any] in
    var filteredDict = [String:Any]()
    dict.forEach({ (key, value) in
        if keysToBeChecked.contains(key) {
            filteredDict[key] = value
            if (value as? Int) == 1 {
                filteredDict["key6"] = "output"
            }
        }
    })
    return filteredDict
}