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.
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] = ...
.
Please try
items.append(dict1)
items.append(dict2)
and so on...
var items: [Dictionary<String,Int>] = []
var dict1 = ["One" : 1, "Two" : 2 ]
var dict2 = ["Three" : 3, "Four" : 4]
var dict3 = ["Five" : 5 , "Six" : 5]
let arrayOfDictionaries: [[String: Int]]
arrayOfDictionaries = [dict1, dict2, dict3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.