2

I have an dictionary like below:

var param = [String: Any]()
param = ["locale": "en",
         "token": "82ETaBYbiz2ZM2Kqg7eL8z3VL0",
         "taskId": 123]

Now I want to add some other values in same dictionary condition based like below:

if userType == "ADMIN" {
    param = ["userType": "ADMIN"]
} else {
    param = ["userType": "USER"]
}

But when I do like the same it replaces old value. So is there any way to perform this? Coz I have lots of conditions and lots of values to add to the dictionary. Please suggest the effective way to handle this.

2 Answers 2

8

You are not using an array, you are using a Dictionary, which is a collection of key-value pairs. To add a new key and value, you would have to subscript the dictionary and add the new value. So your code should be like this:

if userType == "ADMIN" {
    param["userType"] = "ADMIN"
} else {
    param["userType"] = "USER"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, my bad its dictionary. Thanks for your answer.
3

Your code is currently reassigning the whole dictionary to be a new one just containing a key "userType" and an associated value. If you just want to add that key to the pre-existing dictionary, you'd use a subscript:

param["userType"] = "ADMIN"

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.