gpt4 book ai didi

arrays - 在字典中添加键值对 swift

转载 作者:行者123 更新时间:2023-11-30 10:41:12 24 4
gpt4 key购买 nike

鉴于此

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

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

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

我尝试这样做似乎不起作用

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

最佳答案

您可以创建一个包含 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"]]]

关于arrays - 在字典中添加键值对 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56762943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com