如何将值插入到嵌套Swift Dictionary中 [英] How to insert values into a nested Swift Dictionary
问题描述
字典
中: < pre $
var dict = Dictionary< Int,Dictionary< Int,String>>()
dict.updateValue([1:one,2:两个],forKey:1)
dict [1]?[1] // {Someone}
如果var insideDic = dict [1] {
/ /这是一个副本,所以我不能这样插入:
insideDic [3] =three
}
dict //仍然[1:[1 :one,2:two]]
dict [1]?[3] =three//无法分配给这个表达式的结果
dict [1] ?.updateValue(three,forKey:3)//找不到成员updateValue
我认为应该是一个简单的方法来处理它,但我花了一个小时,仍然无法弄清楚。
我可以使用 NSDictionary
,但我真的很想了解如何在Swift中管理嵌套的字典
?
词典是值类型,因此在作业上复制。因此,您将得到内部字典(将是副本),添加新密钥,然后重新分配。
//获取嵌套字典(将是副本)
var inner:Dictionary< Int,String> = dict [1]!
//添加新值
inner [3] =three
//更新外部字典
dict [1] =内
println(dict)// [1:[1:one,2:two,3:three]]
您可以使用其中一个新的实用程序库,例如 ExSwift ,使其有一点简单:
dict [1] = dict [1] !. union([3:three])
这使用 union方法,它结合了两个字典。
I'm trying to insert new key-value pair in dictionary, which nested in another one 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"
I believe should be a simple way to handle it, but I spent an hour and still can't figure it out.
I can use NSDictionary
instead, but I really like to understand how I should manage nested Dictionaries
in Swift?
Dictionarys are value types so are copied on assignment. As a result you are going to have to get the inner dictionary (which will be a copy), add the new key, then re-assign.
// 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]]
You could use one of the new utility libraries such as ExSwift to make this a bit simpler:
dict[1] = dict[1]!.union([3:"three"])
This uses the union method that combines two dictionaries.
这篇关于如何将值插入到嵌套Swift Dictionary中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!