2016-12-18 52 views
0

我創建這樣的如何更改數組字典中元素的值?

var MyArray: [String:[String:[Int]]] = [ 
    "xx": ["x1": [1, 2, 3], "x2": [4, 5, 6], "x3": [7, 8, 9]], 
    "yy": ["y1": [10, 11, 12], "y2": [13, 14, 15], "y3": [16, 17, 18]]] 

字典我怎樣才能在"xx""x1"3更改爲其他號碼? 我不知道這是3號,但我知道,這是在MyArray["xx"]!["x1"]![2]

回答

0

如果你知道你想變出三個數的指數,你可以改變直接使用標["xx"]?["x1"]?[2]數字3。

var myArray = [ 
    "xx": [ 
     "x1": [1, 2, 3], 
     "x2": [4, 5, 6], 
     "x3": [7, 8, 9] 
    ], 
    "yy": [ 
     "y1": [10, 11, 12], 
     "y2": [13, 14, 15], 
     "y3": [16, 17, 18] 
    ] 
] 

array["xx"]?["x1"]?[2] = 4 
1
// example setup 
var myArray: [String:[String:[Int]]] = [ 
    "xx": ["x1": [1, 2, 3], "x2": [4, 5, 6], "x3": [7, 8, 9]], 
    "yy": ["y1": [10, 11, 12], "y2": [13, 14, 15], "y3": [16, 17, 18]]] 

// value to be replaced 
let oldNum = 3 

// value to replace old value by 
let newNum = 4 

// extract the current value (array) for inner key 'x1' (if it exists), 
// and proceed if 'oldNum' is an element of this array 
if var innerArr = myArray["xx"]?["x1"], let idx = innerArr.index(of: oldNum) { 
    // replace the 'oldNum' element with your new value in the copy of 
    // the inner array 
    innerArr[idx] = newNum 

    // replace the inner array with the new mutated array 
    myArray["xx"]?["x1"] = innerArr 
} 

print(myArray) 
/* ["yy": ["y3": [16, 17, 18], "y2": [13, 14, 15], "y1": [10, 11, 12]], 
    "xx": ["x1": [1, 2, 4], "x3": [7, 8, 9], "x2": [4, 5, 6]]] 
         ^ok! */ 

基於以下是問答&答:

更高性能的方法實際上是刪除內部陣列(對於密鑰"x1");變異它;它重新添加到字典

// check if 'oldNum' is a member of the inner array, and if it is: remove 
// the array and mutate it's 'oldNum' member to a new value, prior to 
// adding the array again to the dictionary 
if let idx = myArray["xx"]?["x1"]?.index(of: oldNum), 
    var innerArr = myArray["xx"]?.removeValue(forKey: "x1") { 
    innerArr[idx] = newNum 
    myArray["xx"]?["x1"] = innerArr 
} 

print(myArray) 
// ["yy": ["y3": [16, 17, 18], "y2": [13, 14, 15], "y1": [10, 11, 12]], "xx": ["x1": [1, 2, 4], "x3": [7, 8, 9], "x2": [4, 5, 6]]] 
+0

這可能受益於一些描述。僅有代碼的答案是令人不悅的。解釋爲什麼這個代碼需要/應該被使用。 – rmaddy

+0

@rmaddy我正在用代碼註釋描述進行編輯(現在已包含您的評論後的30秒),但感謝(非常迅速)提醒:) – dfri

+0

@dfri我正在嘗試替換'3 '用一個Int var的變量'Currentindex = 3',它向我顯示以下錯誤:'不能用類型'(of:Int)''的參數列表調用'indexOf',但是爲什麼? – sunbile