如何将项目词典添加到另一个词典中

如何将项目词典添加到另一个词典中

Swift中的数组支持+ =运算符,将一个数组的内容添加到另一个数组。有没有一种简单的方法来为字典做到这一点?

例如:

var dict1 = ["a" : "foo"]var dict2 = ["b" : "bar"]var combinedDict = ... (some way of combining dict1 & dict2 without looping)


婷婷同学_
浏览 633回答 3
3回答

ibeautiful

您可以定义+=运算符Dictionary,例如,func&nbsp;+=&nbsp;<K,&nbsp;V>&nbsp;(left:&nbsp;inout&nbsp;[K:V],&nbsp;right:&nbsp;[K:V])&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(k,&nbsp;v)&nbsp;in&nbsp;right&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;left[k]&nbsp;=&nbsp;v&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;}

暮色呼如

在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]
打开App,查看更多内容
随时随地看视频慕课网APP