Shubham Shubham - 5 months ago 7
Swift Question

Creating Array of Dictionary in Swift

I am new to Swift. I am trying to create an array of dictionary.

var items: [Dictionary<String,Int>] = []
var dict1 = ["One" : 1, "Two" : 2 ]
var dict2 = ["Three" : 3, "Four" : 4]
var dict3 = ["Five" : 5 , "Six" : 5]

items[0] = dict1
items[1] = dict2
items[2] = dict3
items


But it is not getting initialized properly. Playground shows no error but it is not taking dict2 and dict 3. What is wrong with it. Please correct me.

Answer

If you open the console (⇧⌘Y), you can see the error

fatal error: Array index out of range

You should use items.append(dict1) or items.insert(dict1, atIndex: 0) instead of items[0] = ....

Comments