映射字典键以添加值-Swift

时间:2018-07-30 01:17:52

标签: swift dictionary key

我有两个字典:数据字典和结果字典

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]

我想知道如何基于键添加类似的值,并且只有一个字典。

2 个答案:

答案 0 :(得分:3)

假设data是可变的,则应这样做:

data.merge(results, uniquingKeysWith: { $0 + $1 })

答案 1 :(得分:1)

除了Ole`s answer之外,这时还有另外两个-syntactic sugar-选项:

您可以输入为:

data.merge(results, uniquingKeysWith: +)

或作为尾随闭包语法:

data.merge(results) { $0 + $1 }

因此:

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]
*/