你如何将一个项目字典添加到另一个字典中 [英] How do you add a Dictionary of items into another Dictionary

查看:29
本文介绍了你如何将一个项目字典添加到另一个字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Arrays in Swift support the += operator to add the contents of one Array to another. Is there an easy way to do that for a dictionary?

例如:

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var combinedDict = ... (some way of combining dict1 & dict2 without looping)

推荐答案

您可以为 Dictionary 定义 += 运算符,例如,

You can define += operator for Dictionary, e.g.,

func += <K, V> (left: inout [K:V], right: [K:V]) { 
    for (k, v) in right { 
        left[k] = v
    } 
}

这篇关于你如何将一个项目字典添加到另一个字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆