ios - 如何从快速字典数组中获取所选键数组的值及其复杂性

标签 ios swift xcode big-o higher-order-functions

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

1.) 如何在 swift 中使用高阶函数改进/优化以下代码。

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

在下面的响应中,我只想检查 keyToBeChecked 中描述的某些键的值,并且对于该特定键,我需要执行操作。操作完成后,我想向响应添加一个新 key (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
}

关于ios - 如何从快速字典数组中获取所选键数组的值及其复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58707373/

相关文章:

ios - 如何让 UIKit 为我提供自定义转换的转换协调器?

ios - 使用 NSPredicate 进行字符串比较

ios - 获取新创建 Assets 的 URL,iOS 9 风格

ios - 带有 EncryptedCoreData 的架构 i386 的 undefined symbol

swift - 来自 Xcode 和 Swift 包管理器的 Git Push

ios - CocoaPods 不适用于框架目标

swift - UICollectionView更改单元格间距

ios - 如何使用 AVCapturePhoto 包含位置数据?

ios 9 - tableview 单元格在调用 cellForRowAtIndexPath 时向下/向上滚动时跳转

swift - HTTP POST 请求返回尝试从对象[0] 插入 nil 对象?