swift - 为什么值类型的常量实例不能更改其属性而引用类型的常量实例可以?

标签 swift reference constants

我是 Swift 的新手,正在尝试学习属性的概念。我从“swift programming language 2.1”中看到了下面的语句和代码。

struct FixedLengthRange {
    var firstvalue: Int
    let length: Int
}

let rangeOfFourItems = FixedLengthRange(firstvalue: 0, length: 4)
rangeOfFourItems.firstvalue = 8 //error: cannot assign to property: rangeOfFourItems is a "let" constant

书中对错误的解释如下:

This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.

The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.

为什么值类型的常量实例不能更改其属性,而引用类型的常量实例可以?其背后的原因是什么?这本书确实说了如何但没有解释为什么。我认为了解事物现状背后的原因是一种很好的做法。有人可以给我解释一下吗?

最佳答案

why is constant instance of a value type can NOT change its properties

因为值类型被视为一个不可分割的单元:它在赋值时被复制,将它作为参数传递就像一个副本,所以使用 const-ness 锁定了整个 struct。从某种意义上说,rangeOfFourItems 变量表示结构本身,而不是指针或对其的引用。

while constant instance of a reference type can?

声明引用类型的 const 变量也使实例成为常量的说法并不完全正确。只有引用是常量,而不是实例。

如果您考虑一下,这是唯一可以有意义地实现的方法,因为多个变量可以引用同一个引用实例。如果这些变量之一是常量而另一个不是常量,则将非常量引用分配给常量变量不可能锁定引用的对象,这也会锁定非常量引用:

var a = ByRefType()
let b = a; // b is a constant reference to the same instance as "a"
a.property = newValue; // Prohibiting this assignment would be inconsistent

当然,与非常量变量 a 不同,常量变量本身(例如上面的 b)不能被重新赋值。

关于swift - 为什么值类型的常量实例不能更改其属性而引用类型的常量实例可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661753/

相关文章:

c# - 获取包含类的实例

java - 在代码中使用 db 值的正确方法是什么

ios - 禁用位置服务后立即显示警报 View

ios - 从本地通知启动应用程序; VC实例化,但没有出现

c++ - 访问特征矩阵的行 vector 时复制或引用

c++ - 为什么这个程序使用 boost::ref

c++ - 运行 g++ 应用程序时出错。 (字符串加密)

ios - UIImagePickerController - 默认情况下如何访问前置摄像头?

ios - Apple TLS 与 Objective-C 和 Swift 之间的区别

C++ 逗号运算符重载和引用 vector