Swift dictionary with array as value

18,847

Solution 1

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

Solution 2

 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.

Share:
18,847
lascoff
Author by

lascoff

Updated on June 15, 2022

Comments

  • lascoff
    lascoff almost 2 years

    How do you declare a dictionary that has an array as the value? Is this even possible?