在字典Swift中添加键值对

时间:2019-06-25 22:46:52

标签: arrays swift dictionary

给出这个

var applicationPayload =
    [
        "main": [
            "key1": "value1",
            "key2": [
                "inside1": "insideValue1"
            ]
        ]
    ]

如何在key2属性中附加或添加一些内容。我希望结果是这样的

[
    "main": [
        "key1": "value1",
        "key2": [
            "newInside2": "newInsideValue2",
            "inside1": "insideValue1"
        ]
    ]
]

我尝试这样做似乎无效

applicationPayload["main"]["key2"]["newInside2"] = "newInsideValue2"

2 个答案:

答案 0 :(得分:0)

您可以尝试使用keyPath

轻松访问/分配
   // get value of key2
 var res = applicationPayload[keyPath:"main.key2"] as! [String:Any]
   // add the other key
 res["newInside2"] = "newInsideValue2"
   // mutate key2
 applicationPayload[keyPath:"main.key2"] = res

有关键路径的更多信息,请检查https://oleb.net/blog/2017/01/dictionary-key-paths/

答案 1 :(得分:0)

您可以创建一个包含key2当前值的变量,并对其进行修改,然后再将其重写回原始字典中:

import Foundation

var applicationPayload =
    [
        "main": [
            "key1": "value1",
            "key2": [
                "inside1": "insideValue1"
            ]
        ]
    ]

print("Before: \(applicationPayload)")

var key2Value = applicationPayload["main"]?["key2"] as! [String: String]
key2Value["newInside2"] = "newInsideValue2"
applicationPayload["main"]?["key2"] = key2Value

print("After: \(applicationPayload)")

输出:

Before: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1"]]]
After: ["main": ["key1": "value1", "key2": ["inside1": "insideValue1", "newInside2": "newInsideValue2"]]]