我声明并初始化了一个[[String:[String:String]
字典。它在开头是空的,我试图在父键下添加多个值。
var dictionary = [String:[String:String]
// some checks
dictionary[i] = ["name" : name]
dictionary[i] = ["from" : country]
dictionary[i] = ["age" : age]
当我这样做时,我最终只有[key: [String:String]
下的孩子年龄。所以当我使用这种方法时它会被覆盖。
适当的做法是什么
答案 0 :(得分:2)
您的代码正在每行创建一个新词典,并在dictionary
中为键i
分配,因此您最终会得到最后一个词典["age" : age]
您需要创建一个内部字典,为其指定值,然后将其分配给外部字典;
var innerDict = [String:String]()
innerDict["name"] = name
innerDict["from"] = from
innerDict["age"] = age
dictionary[i] = innerDict
但是,我建议您考虑创建一个Struct并将其放在外部字典中而不是使用字典字典
答案 1 :(得分:0)
func insert(key:String, value:String, at k:String) {
var d = dictionary[k] ?? [String:String]()
d[key] = value
dictionary[k] = d
}
以下是如何测试它:
insert("name", value: name, at: i)
insert("from", value: country, at: i)
insert("age", value: age, at: i)
答案 2 :(得分:0)
您可以使用可选链接分配到内部字典,但您需要先创建内部字典。
// create the dictionary of dictionaries
var dictionary = [String:[String:String]]()
// some example constants to make your code work
let i = "abc"
let name = "Fred"
let country = "USA"
let age = "28"
// Use nil coalescing operator ?? to create
// dictionary[i] if it doesn't already exist
dictionary[i] = dictionary[i] ?? [:]
// Use optional chaining to assign to inner dictionary
dictionary[i]?["name"] = name
dictionary[i]?["from"] = country
dictionary[i]?["age"] = age
print(dictionary)
输出:
["abc": ["age": "28", "from": "USA", "name": "Fred"]]
使用这些技巧,这是我的@ matt insert(_:value:at:)
函数的版本:
func insert(key:String, value:String, at k:String) {
dictionary[k] = dictionary[k] ?? [:]
dictionary[k]?[key] = value
}