1

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.

Joshua
  • 40,822
  • 8
  • 72
  • 132
Cameron
  • 185
  • 2
  • 11

2 Answers2

3

Assuming data is mutable, this should do it:

data.merge(results, uniquingKeysWith: { $0 + $1 })
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
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]
*/
Ahmad F
  • 30,560
  • 17
  • 97
  • 143