3

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.

2 Answers 2

5

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] = ....

Sign up to request clarification or add additional context in comments.

2 Comments

I have checked the console, no error is there. And why array index out of range error should be there. I am putting the elements in array contagiously. However items.append() worked for me. But can u explain me what was wrong with my way.
Subscript assignment syntax can't be used to add items to an array in Swift (apparently). That's what append is for. Or, you can use insert(_:atIndex:).
0

Please try

 items.append(dict1)
 items.append(dict2)
 and so on...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.