0

I created a dictionary and it already has several values, however, I now want to add more. And I know that I can add key-value pairs like this:

var Dict = [Int: String] ()
Dict = [1: "one", 0: "zero"]
Dict[2] = "two"
Dict[3] = "tres"

But I was wondering how to add a lot of pairs at the same time, because if they are too many and it would be a really long process to do it like that.

I know this can be done in an Array like this:

Array += [1, 2, 3, 4, 5, 6]

But don't know if the same can be done for dictionaries.

Catalina P.
  • 1
  • 1
  • 3
  • 1
    What exactly do you mean by "*I want to add a lot of pairs at the same time*" – where do these pairs come from? – Hamish Feb 02 '17 at 17:12
  • I mean a Key-Value pair, such as the [1: "one"]. But multiple of them at the same time, like when you add many values at once in an Array: – Catalina P. Feb 02 '17 at 17:17
  • Yeah I understood that, but what I meant was from where are you getting these key-value pairs? Are they hard-coded in or are they coming from some data source? It would be most helpful if you were to add some context to your question. – Hamish Feb 02 '17 at 17:19
  • Please, post a concrete example of the code you are having trouble with. – xpereta Feb 02 '17 at 17:23
  • 1
    I'm new in Swift and coding in general, and I'm just learning about dictionaries, so I'm doing this just as practice, don't hace a data-source or anything, I'm just creating data. I created a dictionary and initialized it with many values, then appended some more, and now I was just wondering if, like in an Array, I can add multiple values at the same time with += or somehow. – Catalina P. Feb 02 '17 at 17:44
  • Updated the post, so you can understand better what I'm asking. – Catalina P. Feb 02 '17 at 17:50
  • You could overload `+=` to do this – see for example [this Q&A](http://stackoverflow.com/q/24051904/2976878). – Hamish Feb 02 '17 at 17:52

1 Answers1

1

There are some tricky things you can do with flatmap, but generally, Swift's Dictionary does not have the append(:Collection) method that Array does, because appending an unknown Dictionary could give you duplicate keys and cause errors. If you want to append another Dictionary, you'll have to iterate over it. This code

var dict1 : [String:String] = ["one" : "two", "three" : "four"]
var dict2 : [String:String] = ["one" : "two", "three" : "five"]
for(key, value) in dict2 {
    dict1[key] = value
}

will replace all duplicate keys with the values in the second Dictionary. If you have no duplicate keys, this will do exactly what you want. If you DO have duplicate keys, then determine which values take priority, and make sure those values are in your dict2.

dylanthelion
  • 1,760
  • 15
  • 23