iAj
iAj

Reputation: 3817

How to update value of dictionary in iOS Swift?

var request: [String: Any] = [

    "Token": "Token",
    "Request": [
        "CityID": "CityID",
        "Filters": [
            "IsRecommendedOnly": "0",
            "IsShowRooms": "0"
        ]
    ]
]
//
print(request)

Console output:

["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "0"]]]

Here I want to update value of "IsShowRooms" key from value "0" to value "1", I was tried different steps but I am unable to do so, can anyone help me out in this?

Upvotes: 0

Views: 384

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15788

You can get the value by typecasting Any to its type and store its value back

if var requestVal = request["Request"] as? [String: Any], var filters = requestVal["Filters"] as? [String: String] {
    filters["IsShowRooms"] = "1"
    requestVal["Filters"] = filters
    request["Request"] = requestVal
}

Output

["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "1"]]]

OR

Instead of storing values in Dictionary create a struct. It will be easier to update its properties

Upvotes: 4

Mahendra
Mahendra

Reputation: 8924

You can do this following way.(Dictionary in swift is treated as value type)

if var reqObj = request["Request"] as? [String: Any] {

  if var obj = reqObj["Filters"] as? [String: Any] {

    obj["IsShowRooms"] = "1"
    reqObj["Filters"] = obj
  }
  request["Request"] = reqObj
}
print(request)

OUTPUT

["Request": ["CityID": "CityID", "Filters": ["IsShowRooms": "1", "IsRecommendedOnly": "0"]], "Token": "Token"]

Upvotes: 1

Related Questions