gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:41 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com