[英]Merge dictionary in swift with unique keys
I am trying to sum of the dictionaries with unique type- 我正在尝试将具有唯一类型的字典相加-
let dict1: [String:Any] = ["type":"steps","value": 100]
let dict2: [String:Any] = ["type":"cal","value": 200]
let dict3: [String:Any] = ["type":"cal","value": 300]
let dict4 : [String:Any] = ["type":"steps","value": 400]
let dict5 : [String:Any] = ["type":"cal","value": 500]
I am just looking for result as - 我只是在寻找结果-
sum is - [["type":"steps","value": 500],["type":"cal","value": 1000]]
I gone through https://developer.apple.com/documentation/swift/dictionary but not found what i required 我经历了https://developer.apple.com/documentation/swift/dictionary,但没有找到我所需要的
Please help with this 请帮忙
You can do it Like that: 您可以这样做:
let dict1: [String:Any] = ["type":"steps","value": 100]
let dict2: [String:Any] = ["type":"cal","value": 200]
let dict3: [String:Any] = ["type":"cal","value": 300]
let dict4 : [String:Any] = ["type":"steps","value": 400]
let dict5 : [String:Any] = ["type":"cal","value": 500]
let array = [dict1,dict2,dict3,dict4,dict5]
let list :[String:[[String:Any]]] = Dictionary(grouping: array, by: {$0["type"] as? String ?? ""})
let result = list.map { (key,value) -> [String:Any] in
let sum = value.reduce(0, {$0 + ($1["value"] as? Int ?? 0)})
return ["type":key , "value":sum]
}
print(result)
OutPut: 输出:
[["type": "cal", "value": 1000], ["type": "steps", "value": 500]]
If your dictionaries always contain the same keys with values of the same type it makes sense to convert them to objects. 如果字典始终包含具有相同类型值的相同键,则可以将它们转换为对象。 It makes summing them way easier. 它使汇总它们的方式更加容易。
let dict1: [String: Any] = ["type":"steps","value": 100]
let dict2: [String: Any] = ["type":"cal","value": 200]
let dict3: [String: Any] = ["type":"cal","value": 300]
let dict4: [String: Any] = ["type":"steps","value": 400]
let dict5: [String: Any] = ["type":"cal","value": 500]
let dicts = [dict1, dict2, dict3, dict4, dict5]
// wrapper class
class Wrapper {
// keys
static let typeKey = "type"
static let valueKey = "value"
// values
var type: String
var value: Int
// init
init?(dict: [String: Any]) {
guard let type = dict[Wrapper.typeKey] as? String, let value = dict[Wrapper.valueKey] as? Int else {
// dict has to contain value & type keys to be valid
return nil
}
self.type = type
self.value = value
}
// converting back to dictionary
func toDict() -> [String: Any] {
return [Wrapper.typeKey: type, Wrapper.valueKey: value]
}
// summing
static func sumWrappers(_ wrappers: [Wrapper]) -> [Wrapper] {
var result: [Wrapper] = []
wrappers.forEach { wrapper in
if let existing = result.first(where: { $0.type == wrapper.type }) {
// wrapper of this type already exists -> increase the value
existing.value += wrapper.value
} else {
// new type of wrapper -> just add it to the result
result.append(wrapper)
}
}
return result
}
}
// usage
let wrappers = dicts.compactMap { Wrapper(dict: $0) } // get valid wrappers
let result = Wrapper.sumWrappers(wrappers) // get sums for all the different types
let resultArray = result.map { $0.toDict() } // contains the final result as array of dictionaries
Result 结果
[["type": "steps", "value": 500], ["type": "cal", "value": 1000]] [[“ type”:“ steps”,“ value”:500],[“ type”:“ cal”,“ value”:1000]]
func sumDict(arrayOfDict: [[String:Any]]) -> [[String:Any]] {
var stepVal = 0, calVal = 0
for dict in arrayOfDict {
if let typeValue = dict["type"] as? String, typeValue == "steps" {
if let val = dict["value"] as? Int {
stepVal += val
}
} else if let typeValue = dict["type"] as? String, typeValue == "cal" {
if let val = dict["value"] as? Int {
calVal += val
}
}
}
let resultDic = [["type":"cal","value": calVal],["type":"steps","value": stepVal]]
return resultDic
}
let dict1: [String:Any] = ["type":"steps","value": 100]
let dict2: [String:Any] = ["type":"cal","value": 200]
let dict3: [String:Any] = ["type":"cal","value": 300]
let dict4: [String:Any] = ["type":"steps","value": 400]
let dict5: [String:Any] = ["type":"cal","value": 500]
let array = [dict1,dict2,dict3,dict4,dict5]
print("sum is - \(sumDict(arrayOfDict: array))")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.