如何在Swift中合并两个Dictionary实例? [英] How to combine two Dictionary instances in Swift?
本文介绍了如何在Swift中合并两个Dictionary实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Swift
将一个Dictionary
附加到另一个Dictionary
?
How do I append one Dictionary
to another Dictionary
using Swift
?
我正在使用AlamoFire
库将JSON
发送到REST server
.
I am using the AlamoFire
library to send a JSON
to a REST server
.
字典1
var dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]
词典2
var dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId: userId
]
]
如何将两个字典结合在一起,制作一个新的字典,如下所示?
let parameters: [String: AnyObject] = [
kFacebook: [
kToken: token
],
kRequest: [
kTargetUserId: userId
]
]
我尝试过dict1 += dict2
,但是出现了编译错误:
I have tried dict1 += dict2
but got a compile error:
二进制运算符'+ ='不能应用于两个'[String:AnyObject]'操作数
Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands
推荐答案
var d1 = ["a": "b"]
var d2 = ["c": "e"]
extension Dictionary {
mutating func merge(dict: [Key: Value]){
for (k, v) in dict {
updateValue(v, forKey: k)
}
}
}
d1.merge(d2)
请参阅很棒的Dollar&分项目 https://github.com/ankurp/Cent/blob/master/Sources /Dictionary.swift
Refer to the awesome Dollar & Cent project https://github.com/ankurp/Cent/blob/master/Sources/Dictionary.swift
这篇关于如何在Swift中合并两个Dictionary实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文