Search code examples
swiftswift-dictionary

Add new entries to a "complex" dictionary


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?


Solution

  • 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.