swift - 是否可以使数组引用不可变,但数组内容可变?
问题描述
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 中,是否可以使数组引用不可变,但数组内容可变?
解决方案
您的问题的答案是“是”和“否”,这取决于您拥有什么。
如果您决定声明一个简单的“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
每个字段都会传播 ,而类则不是这样。
推荐阅读
- javascript - 将文件名从目录添加到对象
- r - R中基于条件组合的数据查询
- ios - 我们能否在将 Objc 对象从 void*“桥接”到 UIKit 对象之前检查它是否被释放?
- c++ - 在具有不同编译器的混合 C/C++ 项目中将 CMake 目标与 OpenMP 链接
- java - 描述 资源路径 位置 类型 方法 run(Class
, String[]) 对于 SpringBootApplication Application.java 类型未定义 - javascript - LWC 4 相关选项列表
- c# - 我如何在这里编写构造函数?C#
- ruby-on-rails - 主键串连外键存在
- bash - 如何使用 bash 命令在字符串的 2 个不同字符之间剪切子字符串?
- node.js - 中度和高度漏洞