合并两个字典

Tim*_*erg 0 arrays dictionary addition swift

我正在学习 Swift,但找不到解决我的问题的方法......

我有两个字典并想将它们合并:

dict1 = ["A": 1, "B": 2, "D": 5]
dict2 = ["A": 3, "C": 9, "D": 4]
Run Code Online (Sandbox Code Playgroud)

结果应该是一个新的字典,例如:

dict3 = ["A": 4, "B": 2, "C": 9, "D": 9]
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 7

您可以使用 Dictionarymerging方法并传递加号(加法运算符)作为uniquingKeysWith参数:

let dict3 = dict1.merging(dict2, uniquingKeysWith: +)  // ["A": 4, "B": 2, "D": 9, "C": 9]
Run Code Online (Sandbox Code Playgroud)

  • 多谢!答案很简单,我找不到它xD (2认同)