您可以使用可選鏈接分配給內部字典,但您需要先創建內部字典。
// 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"]]
使用這些技術,這是我的@馬特的insert(_:value:at:)
功能版本:
func insert(key:String, value:String, at k:String) {
dictionary[k] = dictionary[k] ?? [:]
dictionary[k]?[key] = value
}
這是我的情況下,最好的辦法。謝謝! – senty