I have two dictionaries: a data dict and a results dict
var data = ["flushes": 0.0, "times": 0.0, "glasses": 0.0, "showers": 0.0, "brushings": 0.0, "loads": 0.0, "washings": 0.0, "baths": 252.0, "dishes": 0.0]
let results = ["flushes": 21.0, "times": 0.0, "glasses": 0.0, "showers": 150.0, "brushings": 4.0, "loads": 0.0, "washings": 5.0, "baths": 0.0, "dishes": 9.0]
I am wondering how to add like values based on key and have only one dictionary.
Assuming data
is mutable, this should do it:
data.merge(results, uniquingKeysWith: { $0 + $1 })
In addition to Ole`s answer, at this point there are two other -syntactic sugar- options:
You could type it as:
data.merge(results, uniquingKeysWith: +)
Or as a trailing closure syntax:
data.merge(results) { $0 + $1 }
Hence:
print(data)
/*
["flushes": 21.0,
"times": 0.0,
"glasses": 0.0,
"showers": 150.0,
"brushings": 4.0,
"loads": 0.0,
"washings": 5.0,
"baths": 252.0,
"dishes": 9.0]
*/