Swift:如何组合两个Dictionary实例?

The*_*mad 50 xcode json dictionary ios swift

如何添加一个Dictionary到另一个Dictionary使用Swift

我正在使用该AlamoFire库发送JSONREST server.

字典1

var dict1: [String: AnyObject] = [
            kFacebook: [
                kToken: token
            ]
        ]
Run Code Online (Sandbox Code Playgroud)

字典2

var dict2: [String: AnyObject] = [
        kRequest: [
            kTargetUserId: userId
        ]
    ]
Run Code Online (Sandbox Code Playgroud)

如何将两个词典组合成一个新词典,如下所示?

let parameters: [String: AnyObject] = [
        kFacebook: [
            kToken: token
        ],
        kRequest: [
            kTargetUserId: userId
        ]
    ]
Run Code Online (Sandbox Code Playgroud)

我试过dict1 += dict2但得到了编译错误.

提前致谢!

bla*_*acx 100

我喜欢这种方法:

dicFrom.forEach { (key, value) in dicTo[key] = value }

斯威夫特4

使用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]
Run Code Online (Sandbox Code Playgroud)

这里有2个选项(与大多数在容器上运行的函数一样):

  • merge 改变现有的字典
  • merging 创建一个新词典

  • 这很棒。它允许选择整个字典。有没有办法添加自定义_每个键_逻辑? (2认同)

Shu*_*huo 42

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)
Run Code Online (Sandbox Code Playgroud)

参考令人敬畏的Dollar&Cent项目 https://github.com/ankurp/Cent/blob/master/Sources/Dictionary.swift

  • 由于`Dictionary` 有自己的合并功能,因此不再需要扩展。请参阅 /sf/answers/3053060041/。 (2认同)

emp*_*emp 15

对于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) { (var r, e) in r[e.0] = e.1; return r }

Swift 4有一个新功能: let parameters = dict1.reduce(into: dict2) { (r, e) in r[e.0] = e.1 }

围绕标准库挖这真的很重要:map,reduce,dropFirst,forEach等都是简洁的代码主食.功能位很有趣!


Raj*_*har 10

我们可以使用 merge 关键字以更好的方式合并字典

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]
Run Code Online (Sandbox Code Playgroud)


小智 6

SequenceType.forEach(实现Dictionary)提供了一个优雅的解决方案,将字典的元素添加到另一个字典.

dic1.forEach { dic2[$0] = $1 }
Run Code Online (Sandbox Code Playgroud)

例如

func testMergeDictionaries() {
    let dic1 = [1:"foo"]
    var dic2 = [2:"bar"]

    dic1.forEach { dic2[$0] = $1 }

    XCTAssertEqual(dic2[1], "foo")
}
Run Code Online (Sandbox Code Playgroud)


Leo*_*bus 6

func +=<Key, Value> (lhs: inout [Key: Value], rhs: [Key: Value]) {
    rhs.forEach{ lhs[$0] = $1 }
}

var dic1 = ["test1": 1]

dic1 += ["test2": 2]

dic1  // ["test2": 2, "test1": 1]
Run Code Online (Sandbox Code Playgroud)


Tej*_*ina 5

用于合并 2 个字典的 Swift 4+ 解决方案:

let dict1 = ["a": 1, "b": 2]
let dict2 = ["a": 3, "c": 4]

//In case of duplicate keys, values of dict1 will replace dict2
 let result1 = dict1.merging(dict2) { (current, _) in current } //["a": 1, "b": 2, "c": 4]

//In case of duplicate keys, values  of dict2 will replace dict1
 let result2 = dict1.merging(dict2) { (_, new) in new } //["a": 3, "b": 2, "c": 4]
Run Code Online (Sandbox Code Playgroud)