Prabhu
Prabhu

Reputation: 13335

How do you add a new key to a dictionary in swift?

How do you add a new key to a Dictionary in Swift? I'm getting an error :

This class is not key value coding-compliant for the key address...

Here's my code:

let user = [
     "id": id,
     "name" : name
]

if customer.address != nil {
    let address = [
         "street": customer.address.street,
         "zip": customer.address.zip,
    ]

    user.setValue(address, forKey: "address")
}

UPDATED Code:

var user = [
            "id": customer.id,
            "name" : customer.fullName!,
            "position" : customer.position != nil ? customer.position! : ""
        ]

        if customer.address != nil {
            let address = [
                "street": customer.address!.street,
                "zip":   customer.address!.zip
            ]

            user["address"] = address
        }

Upvotes: 2

Views: 6420

Answers (2)

Nirav D
Nirav D

Reputation: 72440

Simply change you user Dictionary decalration to var instead of constant and then use subscript to add new value with key.

var user: [String: AnyObject] = [
    "id": id,
    "name" : name
]
user["address"] = address

Upvotes: 2

Sahil
Sahil

Reputation: 9226

The problem is that you are trying to add different type values in dictionary. if you want to add different type of values use Any. Any can represent an instance of any type at all.

for example:

var user: [String: Any] = [
  "id": "dd",
  "name" : "ddd"
]

let address = ["street": "ss","zip": "124115"]

user["address"] = address

Upvotes: 6

Related Questions