Untitled

Properties - The Swift Programming Language (Swift 5.6)

솝트세미나 듣다가 프로퍼티에 대해 더 알아보세요 라는 말을 듣고 프로퍼티를 좀 다시 정리해야 겠다는 생각이 들었다.. 그동안 .. 은근슬쩍 눈감았던 이부분..

<aside> 📌 Swift의 프로퍼티 → 클래스, 구조체, 열거형과 관련한 값


  1. Stored Property 저장 프로퍼티: 상수와 변수의 값을 인스턴스 일부로 저장 (클래스, 구조체에서 사용)
  2. Computed Property 연산 프로퍼티: 특정 연산을 수행하여 반환 (클래스, 구조체, 열거형 에서 사용)
  3. Type Property 타입 프로퍼티: 타입자체와 연결 (properties can also be associated with the type itself)

+) Property Observer를 통해 프로퍼티 값이 바뀌는 것을 모니터링하고, 특정한 행동을 취할 수 있다.

</aside>

1️⃣ 저장 프로퍼티

특정 클래스나 구조체에 값을 저장하고 있는 상수(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으로 선언하면 내부 프로퍼티를 변경할 수 없다.

(클래스는 변경 가능하다. 참조타입이어서)

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**