Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

I have been trying to add multiple values for one key in a dictionary.

In objective c we can write like this right:

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

But in Swift how can we write I am trying like this but it is not accessing:

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

Can any one help me out?.

like image 525
Santo Avatar asked Oct 15 '14 14:10

Santo


2 Answers

An array can be created in swift 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"]]

Just to know what you're working with, the type of animalsDic is:

[String: [String]]

equivalent to:

Dictionary<String, Array<String>>
like image 128
Antonio Avatar answered Oct 11 '22 09:10

Antonio


You can't just add commas to separate the elements because they are used by the dictionary to separate key value pairs as well. You should be wrapping the objects in arrays like you are in Objective C. It should look like this.

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

Making animalsDic have the type [String : [String]].

like image 24
Mick MacCallum Avatar answered Oct 11 '22 07:10

Mick MacCallum