iOS 기본 (swift)
[iOS - swift] property 구분 방법 (stored property, computed property, lazy property)
jake-kim
2021. 2. 25. 21:26
Stored property vs Computed property
- stored property는 메모리를 먼저 정해진 후 대입하는 형태이므로, '=' 기호가 존재
- computed property는 계산 후 메모리 공간 정해짐 '='기호가 존재하지 않음
class Sample {
public let config: String = {
return "sample"
}()
public let config2: String = {
return "sample"
}
public let config3: String {
return "sample"
}
public lazy var config4: String = {
return "sample"
}()
public func config5() -> String {
return "sample"
}
}
- 1. '='기호가 존재하므로 stored property이며, 클로저 함수를 대입했으므로 끝에 '()' 기호가 존재
- 2. error발생: '='기호가 존재하므로 "stored property" -> 메모리를 먼저 지정 후 값을 대입하는 형태이므로 블록 '{}'에서 메모리가 정해지면 안되므로 결국 뒤에 있는건 함수가 와야함 '{}()'형태
- 3. error발생: '='기호가 없으므로 computed property지만 'let'으로 지정되어 있기때문에 오류 ('='기호가 없으면 var로 선언되어야 computed property)
- 4. '='기호가 있으므로 stored property이며, 메모리가 먼저 정해진 후 함수를 대입한 형태
- 5. 평범한 함수 형태