2016-12-18 5 views
0

私は、他の数に"xx""x1"の値3を変更することができますどのようにこの配列の辞書の要素の値を変更するには?

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

などの辞書を作成していますか? 私は、これは数3であることを知りませんが、私はそれは、次のQ & Aに基づいて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! */ 

であることを知っている:

よりperformantアプローチは実際にを削除する内側の配列(キー"x1")を削除します。それを突然変異させる。あなたは3の外に変更したい番号のインデックスを知っている場合や、辞書

// 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

関連する問題