Dictionary 如何将值插入嵌套的Swift字典

Dictionary 如何将值插入嵌套的Swift字典,dictionary,collections,swift,Dictionary,Collections,Swift,我正在尝试在dictionary中插入新的键值对,它嵌套在另一个dictionary中: var dict = Dictionary<Int, Dictionary<Int, String>>() dict.updateValue([1 : "one", 2: "two"], forKey: 1) dict[1]?[1] // {Some "one"} if var insideDic = dict[1] { // it is a copy, so I ca

我正在尝试在dictionary中插入新的键值对,它嵌套在另一个
dictionary
中:

var dict = Dictionary<Int, Dictionary<Int, String>>()

dict.updateValue([1 : "one", 2: "two"], forKey: 1)
dict[1]?[1] // {Some "one"}

if var insideDic =  dict[1] {
    // it is a copy, so I can't insert pair this way:
    insideDic[3] = "three"
}

dict // still [1: [1: "one", 2: "two"]]

dict[1]?[3] = "three" // Cannot assign to the result of this expression
dict[1]?.updateValue("three", forKey: 3) // Could not find a member "updateValue"
var dict=Dictionary()
dict.updateValue([1:“一”,2:“两”],forKey:1)
dict[1]?[1]/{某个“一”}
如果var insideDic=dict[1]{
//它是一个副本,因此我不能以这种方式插入对:
insideDic[3]=“三”
}
仍然[1:[1:“一”,2:“两”]
dict[1]?[3]=“三”//无法分配给此表达式的结果
dict[1]?.updateValue(“三”,forKey:3)//找不到成员“updateValue”
我相信这应该是一个简单的方法来处理它,但我花了一个小时,仍然无法找到它。
我可以改用
NSDictionary
,但我真的很想了解我应该如何管理Swift中嵌套的
字典

字典是值类型,因此在赋值时会复制。因此,您必须获取内部字典(它将是一个副本),添加新密钥,然后重新分配

// get the nested dictionary (which will be a copy)
var inner:Dictionary<Int, String> = dict[1]!

// add the new value
inner[3] = "three"

// update the outer dictionary
dict[1] = inner
println(dict) // [1: [1: one, 2: two, 3: three]]

这使用了结合了两个词典的。

可能重复的是,它本质上是相同的。对不起,我第一次错过了。我是否应该链接到它并关闭这一个?嗯…斯威夫特处于最糟糕的状态。我们不应该使用实用程序库来实现这一点。没错,数组和字典行为目前造成了很多混乱。谢谢,现在已经很清楚了。接受这个答案需要认知上的转变。。。感觉很违反直觉。我只希望编译器能对它进行优化,因为在我的实际情况中,这本字典是巨大的。在Swift的当前状态下,性能是个问题,请参阅@IlyaBelikin,您可以通过欺骗使其工作-而不是将字典存储在字典中,创建一个充当字典引用的类,并将其存储在您的“外部”词典中!
dict[1] = dict[1]!.union([3:"three"])