TIL (Today I Learned) 240117_Stored Properties

Danny·2024년 1월 18일

TIL(Today I Learned)

목록 보기
15/34

1월 17일 (수)

🔥학습 내용

프로퍼티(Properties)

  1. Access Stored and computed values that are part of an instance or type
    인스턴스 또는 타입의 한 부분이고, 저장 그리고 연산의 값에 접근할 수 있다고 한다.

  2. Computed properties are provided by classes, structures, and enumerations. Stored properties are provided only by classes and structures.
    Computed properties(연산프로퍼티)는 클래스, 구조체, 열거형에 사용할 수 있고, Stored properties(저장프로퍼티)는 오직 클래스와 구조체와만 사용할 수 있다.

1. Stored Properties(저장 프로퍼티)

[Stored Properties Example]

struct FixedLengthRange {
    var firstValue: Int
    let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
// the range represents integer values 0, 1, and 2
rangeOfThreeItems.firstValue = 6
// the range now represents integer values 6, 7, and 8
  • FixedLengthRange 구조체는 firstValue이라는 이름을 가진 variable stored property와 length라는 이름을 가진 constanct stored property로 정의되어있는 것을 볼 수 있다.
  • 그렇다면, FixedLengthRange 타입으로 정의된 rangeOfThreeItems 인스턴스의 length 프로퍼티의 값을 변경하면 어떻게 될까?
rangeOfThreeItems.length = 4 // Cannot assign to property: 'length' is a 'let' constant 라는 메시지 발생

2. Lazy Stored Properties(지연 저장 프로퍼티)

  • A lazy stored property is a property whose initial value isn’t calculated until the first time it’s used.
    지연 저장 프로퍼티는 직접적으로 사용하기 전까지는 초기화 되지 않는 프로퍼티이다.
  • Constant properties must always have a value before initialization completes, and therefore can’t be declared as lazy.
    상수 프로퍼티는 항상 초기화가 완료가 되어있어야 하기 때문에, 지연 저장 프로퍼티로 사용할 수 없다.
[lazy Stored Properties Example]

class DataImporter {
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a nontrivial amount of time to initialize.
    */
    var filename = "data.txt"
    // the DataImporter class would provide data importing functionality here
}


class DataManager {
    lazy var importer = DataImporter()
    var data: [String] = []
    // the DataManager class would provide data management functionality here
}


let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
// the DataImporter instance for the importer property hasn't yet been created
  • DataManager 클래스 내부에 지연 저장 프로퍼티인 importer가 선언되고, DataImporter의 초기화 된 값을 받는 것을 알 수 있다.
  • DataManager의 인스턴스가 데이터를 추가할 때마다 불필요하게 importer를 선언할 필요가 없으니, lazy라는 키워드 값을 붙여서 지연 저장 프로퍼티를 만든 것으로 볼 수 있다.
print(manager.importer.filename) // 지연 저장 프로퍼티 사용

#. 참고자료

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/properties/

profile
안녕하세요 iOS 개발자 지망생 Danny 입니다.

0개의 댓글