Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

ios - How to combine two Dictionary instances in Swift?

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

I am using the AlamoFire library to send a JSON to a REST server.

Dictionary 1

var dict1: [String: AnyObject] = [
    kFacebook: [
        kToken: token
    ]
]

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

Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...