How to add multiple values ​​for one key in a dictionary using swift

I am trying to add multiple values ​​for one key in a dictionary.

In lens c, we can write this:

NSDictionary *mapping = @{@"B": @[@"Bear", @"Buffalo"]}; 

But in Swift, as we can write, I try so hard, but do not get access:

 var animalsDic = ["B": "Bear","Ball", "C": "Cat","Camel" "D": "Dog", "E": "Emu"] 

Can anyone help me out?

+8
swift
source share
2 answers

An array can be created fast using square brackets:

 ["Bear", "Ball"] 

so the correct way to initialize your dictionary is:

 var animalsDic = ["B": ["Bear","Ball"], "C": ["Cat","Camel"], "D": ["Dog"], "E": ["Emu"]] 

To find out what you are working with, type animalsDic :

 [String: [String]] 

equivalent to:

 Dictionary<String, Array<String>> 
+12
source share

You cannot just add commas to separate elements, because they are used by the dictionary to separate pairs of key values. You should wrap objects in arrays, as in Objective C. This should look like this.

 var animalsDic = ["B": ["Bear","Ball"], "C": ["Cat","Camel"], "D": ["Dog"], "E": ["Emu"]] 

Creating animalsDic is of type [String : [String]] .

+1
source share

All Articles