Properties - The Swift Programming Language (Swift 5.6)
솝트세미나 듣다가 프로퍼티에 대해 더 알아보세요 라는 말을 듣고 프로퍼티를 좀 다시 정리해야 겠다는 생각이 들었다.. 그동안 .. 은근슬쩍 눈감았던 이부분..
<aside> 📌 Swift의 프로퍼티 → 클래스, 구조체, 열거형과 관련한 값
+) Property Observer를 통해 프로퍼티 값이 바뀌는 것을 모니터링하고, 특정한 행동을 취할 수 있다.
</aside>
특정 클래스나 구조체에 값을 저장하고 있는 상수(let)나 변수(var)
// 구조체 예시
struct FixedLengthRange {
var firstValue: Int // variable stored property
let length: Int // constant stored property
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, lenght: 3)
rangeOfThreeItems.firstValue = 6
let
- 상수 저장 프로퍼티 (초기화 이후 변하지 않는다. length
)var
- 변수 저장 프로퍼티구조체의 경우, let으로 선언하면 내부 프로퍼티를 변경할 수 없다.
(클래스는 변경 가능하다. 참조타입이어서)
The same isn’t 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.
let rangeOfThreeItems = FixedLengthRange(firstValue: 0, lenght: 3)
rangeOfThreeItems.firstValue = 6 **// error**