Search

Property Wrapper(박호건)

// property wrapper를 쓰지 않을 때
struct Address {
private var cityname: String = “”
var city: String {
get {cityname}
set{cityname = newValue.upperCase()}
}
}
var address = Address()
address.city = “Chuncheon”
print(address.city) // Chuncheon
// property wrapper를 썼을 때
import UIKit
// 프로퍼티 래퍼 선언
@propertyWrapper
struct FixCase {
private(set) var value: String = ""
var wrappedValue: String {
// 값을 변경하거나 유효성을 검사하는 게터와 세터 코드가 포함된 wrappedValue 프로퍼티를 가져야 함
get {value}
set {value = newValue.uppercased()}
}
init(wrappedValue initialValue: String) {
self.wrappedValue = initialValue
}
}
struct Contact {
@FixCase var name: String
@FixCase var city: String
@FixCase var country: String
}
var contact = Contact(name: "Park Ho Geon", city: "Chuncheon", country: "Korea")
print("\(contact.name), \(contact.city), \(contact.country)" )
// PARK HO GEON, CHUNCHEON, KOREA
Property Wrapper
Swift 공식문서에는 Property Wrapper를 아래와 같이 설명
A property wrapper adds a layer of separation between code that manages how a property is stored and the code that defines a property.
번역하면 "Property Wrapper는 프로퍼티가 저장되는 방법을 관리하는 코드와 프로퍼티를 정의하는 코드 사이의 계층을 추가한다."라는 뜻
장점
간단하게는 프로퍼티 래퍼를 쓰면 프로퍼티에 미리 정의해둔 연산을 사용하기 때문에 반복되는 코드를 줄일 수 있다는 장점
단점
1.
일단 가독성이 떨어진다. 이 코드를 처음부터 끝까지 읽어야 FixCase 생성자로 동작함을 알 수 있다.