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

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

如何将 "xx" 中的 "x1" 中的值 3 更改为其他数字? 我不知道这是数字 3,但我知道它在 MyArray["xx"]!["x1"]![2]

最佳答案

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

关于arrays - 如何更改数组字典中元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213156/

相关文章:

python - 有选择地否定数组中的元素

JavaScript - 特定索引下方的多维数组的列中的目标索引

python - 使用复合键从字典写入 csv 文件

ios - 在 iOS 上映射 UIView

java - 如何使用 ArrayList 和 Array 编写 3 维矩阵

php - 我如何使用从 Ajax 返回的数据?

ios - 快速实现中的 A*路径

ios - 将 NSPredicate 添加到 Core Data 获取请求

ios - UIStackView ios版本之间不同的显示隐藏动画

javascript - 在 ReactJS 中,我如何将 "this"绑定(bind)到 map() 函数内的父组件