iOS 개발 노트
🪴Property Wrapper 본문
프로퍼티 래퍼 (property wrapper)는 프로퍼티가 저장되는 방법을 관리하는 코드와 프로퍼티를 정의하는 코드 사이에 분리 계층을 추가합니다.
프로퍼티 래퍼는 프로퍼티가 저장되는 방법을 관리하는 코드를 재사용할 수 있게 도와주는 기능이다.
@propertyWrapper
프로퍼티 래퍼 내부에는 wrappedValue
라는 연산 프로퍼티가 꼭 선언되어 있어야 하며 struct
, enum
, class
에서 프로퍼티 래퍼를 정의할 수 있다. 프로퍼티 래퍼를 통해 프로퍼티 값 저장 관리 코드를 만들었다면 해당 관리 방법을 적용하고 싶은 프로퍼티에 래퍼를 붙여주는 식으로 사용하면 된다.
@propertyWrapper
struct TwelveOrLess {
private var number = 0
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
}
struct SmallRectanglee {
@TwelveOrLess var heightSize: Int
@TwelveOrLess var widthSize: Int
}
var rectangle = SmallRectanglee()
print(rectangle.heightSize)
// Prints "0"
rectangle.heightSize = 10
print(rectangle.heightSize)
// Prints "10"
rectangle.heightSize = 24
print(rectangle.heightSize)
// Prints "12"
만든 프로퍼티 래퍼는 다음과 같이 재사용이 가능하다.
@propertyWrapper
struct TwelveOrLess {
private var number = 0
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
}
struct SmallRectangle {
@TwelveOrLess var heightSize: Int
@TwelveOrLess var widthSize: Int
}
struct SmallSquare {
@TwelveOrLess var heightSize: Int
@TwelveOrLess var widthSize: Int
}
프로퍼티 래퍼 내부에서 초기값을 지정해준 경우, 따로 Initializer를 통해 초기화 해주는 작업은 생략 가능하다.
@propertyWrapper
struct TwelveOrLess {
private var number: Int = 0
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
}
struct SmallRectangle {
@TwelveOrLess var height: Int
@TwelveOrLess var width: Int
}
var rectangle = SmallRectangle()
print(rectangle.height) // 0
print(rectangle.width) // 0
프로퍼티 래퍼 내부에 init(wrappedValue:)
초기화 메서드를 구현해 초기화하는 방법도 제공된다.
@propertyWrapper
struct TwelveOrLess {
private var number: Int
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
init(wrappedValue: Int) {
number = min(wrappedValue, 12)
}
}
struct SmallRectangle {
@TwelveOrLess(wrappedValue: 0) var height: Int
@TwelveOrLess(wrappedValue: 2) var width: Int
}
원하는대로 값을 변경하거나 추가적인 정보를 제공할 수 있도록 지원하는 Projected Value 기능도 존재한다.
먼저 projectedValue
라는 이름으로 속성을 선언해야하고, 해당 속성은 달러($
) 기호를 통해서 값 접근이 가능하다.
@propertyWrapper
struct TwelveOrLess {
private var number: Int
lazy var projectedValue: String = "현재 값은 \(self.number) 입니다"
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
init(wrappedValue: Int) {
number = min(wrappedValue, 12)
}
}
struct SmallRectangle {
@TwelveOrLess var height: Int
@TwelveOrLess var width: Int
}
var rectangle = SmallRectangle(height: 1, width: 2)
print(rectangle.height) // 1
print(rectangle.$height) // "현재 값은 1 입니다"
'Swift' 카테고리의 다른 글
🪴제네릭(Generic)에 대해서 (0) | 2024.07.22 |
---|---|
🪴Async/Await에 대해서 (0) | 2024.06.23 |
🪴열거형(Enumeration) (0) | 2024.06.12 |
🪴Swift는 Type-Safe한 언어! (0) | 2023.09.22 |
🪴변수명 표기법 (0) | 2023.06.29 |