首页 > 解决方案 > 是否可以使数组引用不可变,但数组内容可变?

问题描述

final在 Java 中,我们可以使用关键字使数组引用不可变,数组内容可变

爪哇

final int[] array = {1, 2, 3};
// Ok. Array content mutable.
array[0] = 9;
// Compiler error. Array reference immutable.
array = new int[]{4, 5, 6};

在 Swift 中,他们更进一步。使用let关键字,将使数组引用和数组内容不可变。

迅速

let array = [1, 2, 3]
// Compiler error. Array content immutable.
array[0] = 9
// Compiler error. Array reference immutable.
array = [4, 5, 6]

在 Swift 中,是否可以使数组引用不可变,但数组内容可变?

标签: swift

解决方案


您的问题的答案是“是”和“否”,这取决于您拥有什么。

如果您决定声明一个简单的“let”常量,则不能修改它。为什么 ?因为它可以防止你产生副作用(并且你有一些优化)。

例如,如果您只想浏览列表并打印值,则无需修改列表。

myArray = [1,2,3]
for element in myArray {
  print(element)
}

为什么它可以很酷?现在,如果您知道不想修改列表,它会阻止您使用可以修改列表的函数。它将节省您的时间并避免一些您不期望的行为。如果你声明 avar并且你没有修改值,Swift 也会告诉你。

此外,如果您使用结构或类,Swift 中不可变的概念会很有趣。

想象一下你有这个结构和这个类:

struct TestStruct {
  var myInt: Int

  init(myInt: Int) {
    self.myInt = myInt
  }

}

struct TestClass {
  var myInt: Int

  init(myInt: Int) {
    self.myInt = myInt
  }

}

在这个结构中,你有myInt一个var. 如果你尝试用 let 常量声明一个TestStructure和一个对象会发生什么?TestClass

let testStruct = Test(myInt: 3)
// Cannot assign to property: 'test' is a 'let' constant
test.myInt = 5
let testClass = Test(myInt: 3)
// It works
test.myInt = 5

在结构中,let每个字段都会传播 ,而类则不是这样。


推荐阅读