问题描述
我直接从 Apple页面
I pulled this example straight from this Apple page
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
,如果您分配实例
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
它说即使将其声明为 var,我们也无法更改其属性值。
it says we can't change its property values even if it is declared as 'var'
这使我想知道如何实现 let
?我希望对其进行任何分配都可以在编译时检测到并显示编译错误。但是在上述情况下,为什么不管结构如何定义,它都适用于结构的每个属性?
This makes me wonder how let
is implemented? I hope any assignments to it can be detected at compile time and show compile error. But in the above case, why does it apply to every property of the structure, regardless of how it is defined?
我试图进行搜索,发现非常困难
I tried to search for this, finding it very difficult to search with keyword 'let' as it is quite common term.
有人可以帮我理解吗?
推荐答案
这是因为结构是值类型。
因此,如果我们有一个变量 rangeOfFourItems
,它是FixedLengthRange结构实例,并且我们想设置 rangeOfFourItems.firstValue
,实际上是从 rangeOfFourItems
存储中提取结构实例并用另一个具有不同 firstValue
的另一个结构实例替换 。
Thus, if we have a variable rangeOfFourItems
that is a FixedLengthRange struct instance, and we want to set rangeOfFourItems.firstValue
, we are actually ripping the struct instance right out of the rangeOfFourItems
storage and replacing it with another struct instance with a different firstValue
.
要想知道这是真的,请使用 var
声明 rangeOfFourItems
并在其上附加一个setter观察器,然后然后更改 rangeOfFourItems.firstValue
:
To see that this is true, declare rangeOfFourItems
with var
and attach a setter observer to it, and then change rangeOfFourItems.firstValue
:
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var rangeOfFourItems = FixedLengthRange(firstValue:1, length:4) {
didSet {
print("Hey, you set me!")
}
}
rangeOfFourItems.firstValue = 2 // Hey, you set me!
这表明仅设置此struct实例的属性实际上会设置struct变量本身。
This shows that merely setting the property of this struct instance actually sets the struct variable itself.
但是在您的代码中,我们无法这样做,因为 rangeOfFourItems
可以防止这种隐式赋值-用 let
声明,这意味着它必须保持不变。因此,在编译器级别阻止设置 rangeOfFourItems.firstValue
。
But in your code, we cannot do that, because rangeOfFourItems
prevents this implicit assignment - it is declared with let
, meaning it must remain a constant. Thus, setting rangeOfFourItems.firstValue
is prevented at compiler level.
(如果FixedLengthRange是 class 而不是结构,它将是引用类型,并且可以在适当位置进行更改,并且设置 rangeOfFourItems.firstValue
是合法的即使 rangeOfFourItems
是用 let
声明的。)
(If FixedLengthRange were a class instead of a struct, it would be a reference type, and would be mutable in place, and setting rangeOfFourItems.firstValue
would be legal even if rangeOfFourItems
was declared with let
.)
这篇关于如何执行“让”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!