Add new entries to a "complex" dictionary

183 views Asked by At

I have a more "complex" dictionary that I am trying to add new entries to. The dictionary code is as follows:

var users: [[String:Any]] = [
    [
        "firstName": "Bill",
        "lastName": "G"
    ]
]

I tried adding a new entry with this code:

users[1]["firstName"] = "Steve"
users[1]["lastName"] = "J"

print(users) // fatal error: Array index out of range

But receive "fatal error: Array index out of range" I looked at several examples but all seem to deal with simpler dictionaries. What am I missing?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

You need to first create an instance of the dictionary and add it to the array, you can then add key:value pairs to it:

var users: [[String:Any]] = [
  [
    "firstName": "Bill",
    "lastName": "G"
  ]
]

users.append([String:Any]())

users[1]["firstName"] = "Steve"
users[1]["lastName"] = "J"

print(users) // [["firstName": "Bill", "lastName": "G"], ["firstName": "Steve", "lastName": "J"]]

You can even do it in a single statement like this:

users.append(["firstName": "Steve", "lastName": "J"])

If you don't append a new element on to the array then when you try to reference the next index it will be out of range.

2
DogCoffee On

This works in a playground

var users: [[String:Any]] = [
    [
        "firstName": "Bill",
        "lastName": "G"
    ]
]

users[0]["firstName"] = "Steve"
users[0]["lastName"] = "J"

users

Using index 0, not 1 like you were using which causes the index out of bounds error

Or the more dynamic approach

var users = [[String:AnyObject]]()

let personA = ["Steve":"J"]
let personB = ["Foo":"Z"]

users.append(personA)
users.append(personB)

users