How to combine two Dictionary instances in Swift?

前端 未结 10 1879
滥情空心
滥情空心 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: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")
    }
    

提交回复
热议问题