如何更改数组字典中元素的值?

时间:2016-12-18 21:36:54

标签: arrays swift dictionary

我创建了一个像这样的词典

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"x1"的{​​{1}}值更改为其他数字? 我不知道这是3号,但我知道它在"xx"

2 个答案:

答案 0 :(得分: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! */

基于以下Q& A:

更高效的方法实际上是删除内部数组(对于键"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]]]

答案 1 :(得分: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