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?.
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>>
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]]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With