如何快速冻结数组?

Far*_*ain 2 arrays immutability swift

在 js 中,我可以在向数组添加一些元素后冻结数组。有什么可以在Swift 中冻结数组吗?

什么是冷冻?

Ans:假设我们有一个数组。我们向该数组添加一些元素。

/* This is javascript code */
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// fruits contains some elements

// Now freeze fruits. After freezing, no one can add, delete, modify this array.
Object.freeze(fruits);
Run Code Online (Sandbox Code Playgroud)

我的问题在这里 - “有什么可以快速冻结数组的东西吗?”

Dáv*_*tor 6

您可以创建数组的不可变副本,但是对象的可变性仅由变量声明控制(let对于不可变和var可变),因此一旦创建了可变对象,就不能使其不可变,反之亦然。

var fruits = ["Banana", "Orange", "Apple", "Mango"]
fruits.append("Kiwi")

let finalFruits = fruits // Immutable copy
finalFruits.append("Pear") // Gives compile-time error: Cannot use mutating member on immutable value: 'finalFruits' is a 'let' constant
Run Code Online (Sandbox Code Playgroud)

  • @DávidPásztor,除非它是一些自定义的 `Collection` 类型,它的行为类似于 `Array` 只有禁用所有可变操作的 `freeze()` 方法 (2认同)