How do you declare a dictionary that has an array as the value? Is this even possible?
Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
Two arrays are required to create a dictionary. One array is used as keys and the other array is used as values. The size of both the arrays should be same, thus making a dictionary with size same as that of the array. Following is the syntax to create a dictionary from two Arrays.
Yes
let myDictionary: [String: [Int]] = ["Hello": [1, 2, 3], "World": [4, 5, 6]]
In fact, you don't even need the explicit type declaration if you assign an initial value in place. It can go as simple as:
let myDictionary = ["Hello": [1, 2, 3], "World": [4, 5, 6]]
To use the value:
println(myDictionary["Hello"][0]) // Print 1
println(myDictionary["World"][0]) // Print 4
var dictionary : [String:[AnyObject]]
var dictionary2 = [String:[AnyObject]]()
You can change AnyObject for any class or use it like AnyObject itself if you don't know the class that will be in the array.
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