Map Dictionary Keys to add values - Swift [closed]

2019-08-02 14:43发布

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.

2条回答
祖国的老花朵
2楼-- · 2019-08-02 15:29

Assuming data is mutable, this should do it:

data.merge(results, uniquingKeysWith: { $0 + $1 })
查看更多
放我归山
3楼-- · 2019-08-02 15:34

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]
*/
查看更多
登录 后发表回答