如何使用 Swift 将一个 Dictionary
附加到另一个 Dictionary
?
我正在使用 AlamoFire
库将 JSON 内容发送到 REST服务器。
字典 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
,但出现编译错误:
Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands
最佳答案
我喜欢这种方法:
dicFrom.forEach { (key, value) in dicTo[key] = value }
Swift 4 和 5
随着 Swift 4,Apple 引入了一种更好的方法来合并两个字典:
let dictionary = ["a": 1, "b": 2]
let newKeyValues = ["a": 3, "b": 4]
let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]
let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["b": 4, "a": 3]
这里有 2 个选项(与大多数在容器上运行的函数一样):
merge
改变现有字典合并
返回一个新字典https://stackoverflow.com/questions/26728477/
相关文章:
javascript - 是否有任何将 json 转换为 url 参数的 native 函数?
java - jackson JSON : get node name from json-tree
java - 如何解析嵌套 JSON 结果中的动态 JSON 键?
java - 在 Spring Boot 中返回 JSON 对象作为响应
json - Postgres JSON 数据类型 Rails 查询
javascript - 从名称、值 JSON 数组中获取一项
javascript - 如何使用 JSON 数据填充选择框的选项?