How to combine two Dictionary instances in Swift?

前端 未结 10 1881
滥情空心
滥情空心 2020-12-01 04:13

How do I append one Dictionary to another Dictionary using Swift?

I am using the AlamoFire library to send a

相关标签:
10条回答
  • 2020-12-01 04:45

    I love this approach:

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

    Swift 4 and 5

    With Swift 4 Apple introduces a better approach to merge two dictionaries:

    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):

    • merge mutates an existing dictionary
    • merging returns a new dictionary
    0 讨论(0)
  • 2020-12-01 04:45

    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.

    Change it to var keyword then it will work for you.

    var dict1: [String: AnyObject] = [
                kFacebook: [
                    kToken: token
                ]
            ]
    
    var dict2: [String: AnyObject] = [
            kRequest: [
                kTargetUserId: userId
            ]
        ]
    
    dict1 += dict2
    
    0 讨论(0)
  • 2020-12-01 04:48

    SequenceType.forEach (implemented by Dictionary) provides an elegant solution to add a dictionary's elements to another dictionary.

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

    For example

    func testMergeDictionaries() {
        let dic1 = [1:"foo"]
        var dic2 = [2:"bar"]
    
        dic1.forEach { dic2[$0] = $1 }
    
        XCTAssertEqual(dic2[1], "foo")
    }
    
    0 讨论(0)
  • 2020-12-01 04:50

    We can merge dictionaries in a better way using merge keyword

    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]
    
    0 讨论(0)
提交回复
热议问题