1. Property Wrapper

Swift 5.1 에 추가된 기능으로 Property Wrapper는 반복되는 로직들을 프로퍼티 자체에 연결할 수 있다.

Property Wrapper의 필요성

예를 들어 내가 아래와 같은 코드를 작성했다고 보자. 그러면 두 개의 다른 구조체에 반복되는 형식이 있음을 발견할 수 있을 것이다. 바로 get & set 구문이 반복됨을 볼 수 있다. 이런 로직들을 Property Wrapper를 활용해서 프로퍼티 자체에 연결할 수 있어 보일러플레이트 코드와 코드 재사용성을 높혀줍니다.

즉, 프로퍼티 래퍼를 정의해서 관리 코드를 한번만 작성해준 후, 여러 프로퍼티들에 프로퍼티 래퍼를 적용하여 관리 코드를 재사용하는 방법을 활용해보자~ 이것이다!

struct Animal {
    private var height: Int = 0
    private var weigth: Int = 0
    
    var bmi: Int {
        get { return weigth / height * height }
        set { self.bmi = newValue}
    }
}

struct Human {
    private var height: Int = 0
    private var weigth: Int = 0
    
    var bmi: Int {
        get { return weigth / height * height }
        set { self.bmi = newValue}
    }
}

2. Property Wrapper 정의하기

i) @propertyWrapper 이니셜라이져

ii) wrappedValue property 를 정의한 structure, enumeration, class를 만든다.

@propertyWrapper
struct BMI {
    private var height: Double = 0
    private var weight: Double = 0
    
    var wrappedValue: Double {
        get { return weight / (height * height) }
        set { self.wrappedValue = newValue}
    }
    
    init(height: Double, weight: Double) {
        self.height = height
        self.weight = weight
    }
}

3. Property Wrapper 사용하기

프로퍼티 이름 앞에 wrapper name을 적어줌으로써 wrapper를 적용할 수 있다!

struct Animal {
    @BMI var bmi: Double
}

struct Human {
    @BMI var bmi: Double
}

let animal = Animal(bmi: BMI(height: 200, weight: 100))
let human = Human(bmi: BMI(height: 300, weight: 300))
print(animal.bmi)
print(human.bmi)

+) 초기화? (.init의 이유)

4. Property Wrapper 활용하기