Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift dictionary with array as value

Tags:

ios

swift

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

like image 253
lascoff Avatar asked Nov 21 '14 16:11

lascoff


People also ask

What is dictionary of array in Swift?

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.

How do you create a dictionary array?

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.


2 Answers

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
like image 60
yusuke024 Avatar answered Oct 13 '22 04:10

yusuke024


 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.

like image 20
Себастьян Толедо Avatar answered Oct 13 '22 04:10

Себастьян Толедо