1

Just starting to learn Swift and was wondering if there was a way to quickly add multiple keys and values into a dictionary.

The reason I ask is that for the Array, we can quickly add new things to the list with the .append syntax, for example:

var newArray = ["ArrayItem1"]
var appendItems = ["ArrayItem2", "ArrayItem3", "ArrayItem4"]
newArray += appendItems

Is there such a short way to do it for Dictionaries?

  • 1
    Do you mean append multiple dictionaries? [How do you add a Dictionary of items into another Dictionary](http://stackoverflow.com/questions/24051904/how-do-you-add-a-dictionary-of-items-into-another-dictionary) – JAL Jan 15 '16 at 00:16

2 Answers2

2

You can subscript the dictionary using the key. Read the documentation here, under the Collection Type section.

var dictionary = [String:String]()

dictionary["oneKey"] = "a_value"
dictionary["twoKey"] = "a_value"

EDIT

If you wanted to do more than one at a time:

var dictionary: [String: String] = ["oneKey": "a_value", "twoKey": "a_value"]

Then append:

dictionary["threeKey"] = "a_value"
Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
0

In code:

var testdic:[String:Int] = ["item": 1, "item2": 2]
Tristan
  • 3,301
  • 8
  • 22
  • 27
tzurkan
  • 26
  • 2