ios 如何在 Swift 中组合两个 Dictionary 实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26728477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine two Dictionary instances in Swift?
提问by The Nomad
How do I append one Dictionary
to another Dictionary
using Swift
?
如何使用将一个附加Dictionary
到另一个?Dictionary
Swift
I am using the AlamoFire
library to send a JSON
to a REST server
.
我正在使用AlamoFire
库将 a 发送JSON
到REST server
.
Dictionary 1
字典 1
var dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]
Dictionary 2
字典 2
var dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId: userId
]
]
How do I combine the two dictionaries to make a new dictionary as shown below?
如何组合两个字典来制作一个新的字典,如下所示?
let parameters: [String: AnyObject] = [
kFacebook: [
kToken: token
],
kRequest: [
kTargetUserId: userId
]
]
I have tried dict1 += dict2
but got a compile error:
我试过了,dict1 += dict2
但编译错误:
Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands
二元运算符“+=”不能应用于两个“[String : AnyObject]”操作数
采纳答案by Shuo
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)
Refer to the awesome Dollar & Cent project https://github.com/ankurp/Cent/blob/master/Sources/Dictionary.swift
参考很棒的 Dollar & Cent 项目 https://github.com/ankurp/Cent/blob/master/Sources/Dictionary.swift
回答by blackjacx
I love this approach:
我喜欢这种方法:
dicFrom.forEach { (key, value) in dicTo[key] = value }
dicFrom.forEach { (key, value) in dicTo[key] = value }
Swift 4 and 5
斯威夫特 4 和 5
With Swift 4 Apple introduces a better approach to merge two dictionaries:
在 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]
You have 2 options here (as with most functions operating on containers):
您在这里有 2 个选项(与大多数在容器上运行的函数一样):
merge
mutates an existing dictionarymerging
returns a new dictionary
merge
改变现有字典merging
返回一个新字典
回答by emp
For Swift >= 2.2:let parameters = dict1.reduce(dict2) { r, e in var r = r; r[e.0] = e.1; return r }
对于 Swift >= 2.2:let parameters = dict1.reduce(dict2) { r, e in var r = r; r[e.0] = e.1; return r }
For Swift < 2.2:let parameters = dict1.reduce(dict2) { (var r, e) in r[e.0] = e.1; return r }
对于 Swift < 2.2:let parameters = dict1.reduce(dict2) { (var r, e) in r[e.0] = e.1; return r }
Swift 4 has a new function:
let parameters = dict1.reduce(into: dict2) { (r, e) in r[e.0] = e.1 }
Swift 4 有一个新功能:
let parameters = dict1.reduce(into: dict2) { (r, e) in r[e.0] = e.1 }
It's really important to dig around the standard library: map
, reduce
, dropFirst
, forEach
etc. are staples of terse code. The functional bits are fun!
挖周围的标准库这是非常重要的:map
,reduce
,dropFirst
,forEach
等都是简洁的代码的主食。功能位很有趣!
回答by Leo Dabus
func +=<Key, Value> (lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach{ lhs[dic1.forEach { dic2[func testMergeDictionaries() {
let dic1 = [1:"foo"]
var dic2 = [2:"bar"]
dic1.forEach { dic2[merging:
["b": [1, 2], "s": Set([5, 6]), "a": 1, "d": ["x": 2]]
with
["b": [3, 4], "s": Set([6, 7]), "a": 2, "d": ["y": 4]]
yields:
["b": [1, 2, 3, 4], "s": Set([5, 6, 7]), "a": 2, "d": ["y": 4, "x": 2]]
] = }
XCTAssertEqual(dic2[1], "foo")
}
] = }
] = }
}
var dic1 = ["test1": 1]
dic1 += ["test2": 2]
dic1 // ["test2": 2, "test1": 1]
回答by rhooke
SequenceType.forEach
(implemented by Dictionary
) provides an elegant solution to add a dictionary's elements to another dictionary.
SequenceType.forEach
(由 实现Dictionary
)提供了一个优雅的解决方案来将一个字典的元素添加到另一个字典中。
import UIKit
private protocol Mergable {
func mergeWithSame<T>(right: T) -> T?
}
public extension Dictionary {
/**
Merge Dictionaries
- Parameter left: Dictionary to update
- Parameter right: Source dictionary with values to be merged
- Returns: Merged dictionay
*/
func merge(right:Dictionary) -> Dictionary {
var merged = self
for (k, rv) in right {
// case of existing left value
if let lv = self[k] {
if let lv = lv as? Mergable where lv.dynamicType == rv.dynamicType {
let m = lv.mergeWithSame(rv)
merged[k] = m
}
else if lv is Mergable {
assert(false, "Expected common type for matching keys!")
}
else if !(lv is Mergable), let _ = lv as? NSArray {
assert(false, "Dictionary literals use incompatible Foundation Types")
}
else if !(lv is Mergable), let _ = lv as? NSDictionary {
assert(false, "Dictionary literals use incompatible Foundation Types")
}
else {
merged[k] = rv
}
}
// case of no existing value
else {
merged[k] = rv
}
}
return merged
}
}
extension Array: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Array {
return (self + right) as? T
}
assert(false)
return nil
}
}
extension Dictionary: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Dictionary {
return self.merge(right) as? T
}
assert(false)
return nil
}
}
extension Set: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Set {
return self.union(right) as? T
}
assert(false)
return nil
}
}
var dsa12 = Dictionary<String, Any>()
dsa12["a"] = 1
dsa12["b"] = [1, 2]
dsa12["s"] = Set([5, 6])
dsa12["d"] = ["c":5, "x": 2]
var dsa34 = Dictionary<String, Any>()
dsa34["a"] = 2
dsa34["b"] = [3, 4]
dsa34["s"] = Set([6, 7])
dsa34["d"] = ["c":-5, "y": 4]
//let dsa2 = ["a": 1, "b":a34]
let mdsa3 = dsa12.merge(dsa34)
print("merging:\n\t\(dsa12)\nwith\n\t\(dsa34) \nyields: \n\t\(mdsa3)")
For example
例如
let dict1: [String: AnyObject] = ["kFacebook": ["kToken": "token"]]
let dict2: [String: AnyObject] = ["kRequest": ["kTargetUserId": "userId"]]
var combinedAttributes : NSMutableDictionary!
combinedAttributes = NSMutableDictionary(dictionary: dict1)
combinedAttributes.addEntriesFromDictionary(dict2)
println(combinedAttributes)
回答by Chris Conover
My needs were different, I wanted to merge and not clobber.
我的需求不同,我想合并而不是破坏。
{
kFacebook = {
kToken = token;
};
kRequest = {
kTargetUserId = userId;
};
I was hoping for a simpler solution, but this is what I ended up with. The challenge was in hopping from dynamic typing to static typing, and I used protocols to solve this.
我希望有一个更简单的解决方案,但这就是我最终得到的。挑战在于从动态类型跳到静态类型,我使用协议来解决这个问题。
Also worthy of note is that when you use the dictionary literal syntax, you actually get the foundation types, which do not pick up the protocol extensions. I aborted my efforts to support those as I couldn't find an easy to to validate the uniformity of the collection elements.
另外值得注意的是,当您使用字典字面量语法时,您实际上获得了基础类型,而这些类型并没有选择协议扩展。我放弃了支持这些的努力,因为我找不到一个简单的方法来验证集合元素的一致性。
extension Dictionary {
func merge(dict: Dictionary<Key,Value>) -> Dictionary<Key,Value> {
var mutableCopy = self
for (key, value) in dict {
// If both dictionaries have a value for same key, the value of the other dictionary is used.
mutableCopy[key] = value
}
return mutableCopy
}
}
回答by Wolverine
Try This Approach
试试这个方法
var dictionary = ["a": 1, "b": 2]
/// Keeping existing value for key "a":
dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
// ["b": 2, "a": 1, "c": 4]
It will Print Following :
它将打印以下内容:
var dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]
var dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId: userId
]
]
dict1 += dict2
}
}
Hope it helps !!
希望能帮助到你 !!
回答by Pallavi
You can use the below code to combine two dictionary instances in Swift:
您可以使用以下代码在 Swift 中组合两个字典实例:
##代码##回答by Raja Jawahar
We can merge dictionaries in a better way using merge keyword
我们可以使用 merge 关键字以更好的方式合并字典
##代码##回答by Meenakshi
You are using let keyword to declare the dictionary so you can't make the changes to your dictionary as it is used to declare constant.
您正在使用 let 关键字来声明字典,因此您无法对字典进行更改,因为它用于声明常量。
Change it to var keyword then it will work for you.
将其更改为 var 关键字,然后它将为您工作。
##代码##