2016-05-27 57 views
0

我聲明並初始化了一個[[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]未成年鍵作爲一個孩子。所以當我使用這種方法時,它會被覆蓋。

什麼是做

回答

2

您的代碼正在對每行一個新的字典,並在dictionary關鍵i分配此的適當的方式,讓你結束了最後的字典["age" : age]

您需要創建一個內部字典,將值賦給它,然後將它賦值給你的外部字典;

var innerDict = [String:String]() 
innerDict["name"] = name 
innerDict["from"] = from 
innerDict["age"] = age 

dictionary[i] = innerDict 

我會然而建議,你看看創建一個結構,把在你的外詞典,而不是使用字典

+0

這是我的情況下,最好的辦法。謝謝! – senty

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) 
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"]] 

使用這些技術,這是我的@馬特的insert(_:value:at:)功能版本:

func insert(key:String, value:String, at k:String) { 
    dictionary[k] = dictionary[k] ?? [:] 
    dictionary[k]?[key] = value 
}