user3766930 user3766930 - 2 months ago 5
iOS Question

how can I add a key and it's value to a dictionary in Swift?

I have the following variable in Swift:

var params = [
"long": lon,
"lat": lat,
"radius": radius,
"deleted": "false"
]


and I would like to add a new pair to it:

"username": "blablah"


how can I do it? I tried with:

params.setValue("blablah", forKey: "username")


but it threw error:

...this class is not key value coding-compliant for the key username.'

Answer

Two issues. First, there is not enough information for the compiler to determine the dictionary type, so it should be specified. Also, use subscript notation to set the new value. See below:

var params: [String : Any] = [
    "long": lon,
    "lat": lat,
    "radius": radius,
    "deleted": "false"
]

params["username"] = "blablah"
Comments