Swift
[Swift] Property Wrapper
Sky Titan
2022. 2. 13. 13:07
728x90
Properties — The Swift Programming Language (Swift 5.6)
Properties Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties a
docs.swift.org
Property Wrapper
- Property Wrapper는 프로퍼티를 정의하는 코드와 프로퍼티가 어떻게 저장되는지 관리하는 코드를 분리하는 레이어를 추가한다.
- 예를 들어, thread safety를 체크하거나 혹은 데이터를 데이터베이스에 저장하는 프로퍼티들을 가지고 있다고 가정했을 때, 기존엔 모든 프로퍼티에 대해서 해당 코드들을 작성해야한다
- 하지만 Property Wrapper를 사용한다면 프로퍼티를 관리하는 코드를 Property Wrapper를 정의할 때 한 번만 작성하고 그것을 재사용할 수 있다.
정의
- Property Wrapper를 정의하기 위해서, structure, enumeration, class와 같이 Property Wrapper가 사용될 수 있는 객체를 정의해야하며 해당 객체는 wrappedValue 프로퍼티를 정의하고 있어야 한다.
- 정의한 객체 앞에 @propertyWrapper 라는 프로퍼티 래퍼를 붙인다.
Example
import UIKit
// 무조건 2를 곱한 뒤 저장하게 하는 propertyWrapper 선언
@propertyWrapper
struct Doubling<T: Numeric> {
var wrappedValue: T = 1 {
didSet {
self.wrappedValue = 2 * wrappedValue
}
}
}
class Example {
@Doubling
static var originNumber: Double = 1
}
Example.originNumber = 3
print(Example.originNumber) // 6.0
728x90