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?
我认为这应该是一个简单的方法来处理它,但我花了一个小时还是搞不清楚。我可以使用NSDictionary,但我真的很想了解如何在Swift中管理嵌套字典?
2 个解决方案
#1
2
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:
您可以使用一个新的实用程序库,如ExSwift,使其更简单一点:
dict[1] = dict[1]!.union([3:"three"])
This uses the union method that combines two dictionaries.
这使用了合并两个字典的union方法。
#2
0
Better declare it as a NSMutableDictionary
and you can use setValue(value: , forKeyPath)
最好将它声明为NSMutableDictionary,并使用setValue(value:, forKeyPath)
#1
2
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:
您可以使用一个新的实用程序库,如ExSwift,使其更简单一点:
dict[1] = dict[1]!.union([3:"three"])
This uses the union method that combines two dictionaries.
这使用了合并两个字典的union方法。
#2
0
Better declare it as a NSMutableDictionary
and you can use setValue(value: , forKeyPath)
最好将它声明为NSMutableDictionary,并使用setValue(value:, forKeyPath)