var request: [String: Any] = [
"Token": "Token",
"Request": [
"CityID": "CityID",
"Filters": [
"IsRecommendedOnly": "0",
"IsShowRooms": "0"
]
]
]
//
print(request)
控制台输出:
["Token": "Token", "Request": ["CityID": "CityID", "Filters": ["IsRecommendedOnly": "0", "IsShowRooms": "0"]]]
在这里我想将“ IsShowRooms” 键的值从值“ 0” 更新为值“ 1” ,但尝试了不同的方法步骤,但我无法执行此操作,有人可以帮助我吗?
答案 0 :(得分:4)
您可以通过将Any转换为类型来获取值并将其值存储回去
if var requestVal = request["Request"] as? [String: Any], var filters = requestVal["Filters"] as? [String: String] {
filters["IsShowRooms"] = "1"
requestVal["Filters"] = filters
request["Request"] = requestVal
}
输出
[“令牌”:“令牌”,“请求”:[“ CityID”:“ CityID”,“过滤器”:[“ IsRecommendedOnly”:“ 0”,“ IsShowRooms”:“ 1”]]]] >
OR
创建结构而不是在Dictionary中存储值。更新其属性会更容易
答案 1 :(得分:1)
您可以按照以下方式进行操作。(迅速将字典视为值类型)
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)
输出
["Request": ["CityID": "CityID", "Filters": ["IsShowRooms": "1", "IsRecommendedOnly": "0"]], "Token": "Token"]