我是Swift的新手,正在嘗試學習Property的概念。我從「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.
爲什麼值類型的常量實例無法改變其性質,而引用類型的常數實例可以?它背後的原因是什麼?這本書確實說了如何,但沒有解釋爲什麼。我認爲,理解背後的原因是很好的做法。有人請向我解釋一下嗎?
對一個值類型實例的常量引用意味着引用本身不能被改變爲指向任何其他值類型實例,如果我理解正確,它不應該影響值類型本身或其屬性。那麼爲什麼這會使值類型的屬性不可變?這不像是可以有其他引用這種特定的值類型。 – paulvs
非常感謝您的詳細解釋! – Thor