如何在swift中附加到字典数组中的特定字典?

时间:2016-11-06 14:53:15

标签: swift

我的数据结构:

var defs = [["a":"b","c":"d"],["e":"f","g":"h"]]

我尝试了以下内容:

dict[1]["testKey"] = "testValue"

试图达到以下目的:

defs = [["a":"b","c":"d"],["e":"f","g":"h","testKey":"testValue"]]

但这不起作用。有没有人有一个好的解决方案?

2 个答案:

答案 0 :(得分:1)

您的代码中有拼写错误(我发现您使用的是dict而不是defs,但这样可以正常使用:

var defs = [
    [
        "a": "b",
        "c": "d"
    ],
    [
        "e": "f",
        "g": "h"
    ]
]

defs[1]["key"] = "value"
print(defs[1]["key"]) // "Optional("value")\n"

答案 1 :(得分:0)

 var defs = [["a":"b","c":"d"],["e":"f","g":"h"]]
 defs[1]["testKey"] = "testValue"
 print(defs)

打印:

[["a": "b", "c": "d"], ["e": "f", "testKey": "testValue", "g": "h"]]

defs数组中包含的元素属于Dictionary类型,根据定义,它们是无序的。如果订单有问题,您必须使用其他收集类型。