arrays - Swift 数组和字典的不变性

标签 arrays dictionary swift

Swift 的“不可变数组”允许更新操作的预期设计是什么? 然而,仅“不可变字典”就可以免除这种特殊行为。你的想法...

let newArray = ["1","3","4"] // Immutable <String> array 'newArray'
newArray[1]="2"//update index 1 with the value 2 (no error)
newArray[2]="3"//update index 2 with the value 3 (no error)

let newDictionary = [1 : "one", 2 : "third"]//Immutable <Int,String> Dictionary 'newDictionary'
newDictionary[2] = "second" // update 2 keyed value by "third" (throws error)
  1. 为什么不可变数组单独允许更新操作,为什么不可变字典不允许更新操作。

  2. 在文档中写道,为了获得最佳性能,请将固定大小的数组指定为不可变(常量)数组。在这个不可变数组上执行的最佳操作是什么?想法....

最佳答案

字典和数组在使用时复制值

来自 Swift 书籍

数组:

“For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. ”

因此,只要不更改数组的大小,常量变量仍然使用相同的大小,并且我们的常量仍然指向旧值。

字典:

“Whenever you assign a Dictionary instance to a constant or variable, or pass a Dictionary instance as an argument to a function or method call, the dictionary is copied at the point that the assignment or call takes place.”

所以对于字典来说,每次你用它做某事时,它都会复制自身并分配回变量。这违反了 let

的规则

这是字典复制的证明

class Test {
    var newDictionary: Dictionary<Int,String> = [:] {
        didSet {
            println("reset")
        }
    }

    func test() {
        newDictionary = [1 : "one", 2 : "third"]
        newDictionary[2] = "second"
    }
}

Test().test()

输出为

reset
reset

编辑:即使数组在更新值时也会调用didSet。这无法证明里面发生了什么,只有苹果知道

关于arrays - Swift 数组和字典的不变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24278359/

相关文章:

javascript - 我有这个排序数组,我想根据点添加位置值。如果点相同位置将相同

python - 如何使用另一个 numpy 数组修改 pandas 数据框中的所有值

c - 在多维数组的 Leu 中使用哈希表

python - 将平面数组值转换为列向量

html - 图像 map - 国家

string - 如何将函数添加到 Swift 作为 String 的扩展以简化使用

ios - UITableViewCell 掩码选择区域/选择区域的大小?

ios - 在 SwiftUI 中实现外部显示器支持

dictionary - 如何比较 map 的身份或本例中发生了什么?

vb.net - 如何在vb.net中迭代字典?