Santo
Santo

Reputation: 1651

How to add multiple values for one key in a dictionary using 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?.

Upvotes: 9

Views: 21043

Answers (2)

Antonio
Antonio

Reputation: 72760

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

Upvotes: 15

Mick MacCallum
Mick MacCallum

Reputation: 130212

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]].

Upvotes: 1

Related Questions