如何将项目词典添加到另一个词典中Swift中的数组支持+ =运算符,将一个数组的内容添加到另一个数组。有没有一种简单的方法来为字典做到这一点?例如:var dict1 = ["a" : "foo"]var dict2 = ["b" : "bar"]var combinedDict = ... (some way of combining dict1 & dict2 without looping)
3 回答
![?](http://img1.sycdn.imooc.com/5458463b0001358f02200220-100-100.jpg)
ibeautiful
TA贡献1993条经验 获得超5个赞
您可以定义+=
运算符Dictionary
,例如,
func += <K, V> (left: inout [K:V], right: [K:V]) { for (k, v) in right { left[k] = v } }
![?](http://img1.sycdn.imooc.com/53339fdf00019de902200220-100-100.jpg)
暮色呼如
TA贡献1853条经验 获得超9个赞
在Swift 4中,应该使用merging(_:uniquingKeysWith:):
例:
let dictA = ["x" : 1, "y": 2, "z": 3]
let dictB = ["x" : 11, "y": 22, "w": 0]
let resultA = dictA.merging(dictB, uniquingKeysWith: { (first, _) in first })
let resultB = dictA.merging(dictB, uniquingKeysWith: { (_, last) in last })
print(resultA) // ["x": 1, "y": 2, "z": 3, "w": 0]
print(resultB) // ["x": 11, "y": 22, "z": 3, "w": 0]
- 3 回答
- 0 关注
- 675 浏览
添加回答
举报
0/150
提交
取消