可以说我得到了以下答复。我想从以下操作中了解两件事。
1.)如何迅速使用高阶函数改进/优化以下代码。
2.)还想知道代码的当前复杂性以及您可能建议的任何优化代码的复杂性。
在下面的响应中,我只想按keysToBeChecked中所述检查某些键的值,对于该特定键,我需要执行一个操作。操作完成后,我想向响应中添加一个新的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/