屬性包裝器就是對屬性的get和set方法經(jīng)過包裝處理,例如我們實現(xiàn)一個MyColor結(jié)構(gòu)體,允許用戶傳入R,G,B三種顏色的值,但是RGB的值是限定在0-255之間,如何防范用戶傳入錯誤的值呢,此時我們可以實現(xiàn)自定義屬性包裝器,對R,G,B三種顏色的值進行包裝,讓其符合顏色的0-255之間的要求,示例代碼如下:
@propertyWrapper
struct ClamppedValue {
private var storedValue: Int = 0
var wrappedValue: Int {
get {
return self.storedValue
}
set {
if newValue < 0 {
self.storedValue = 0
} else if newValue > 255 {
self.storedValue = 255
} else {
self.storedValue = newValue
}
}
}
init(wrappedValue initialValue: Int) {
self.wrappedValue = initialValue
}
}
struct MyColor {
@ClamppedValue var red: Int
@ClamppedValue var green: Int
@ClamppedValue var blue: Int
}
let color: MyColor = MyColor(red: 50, green: 500, blue: 50)
print("color.red is \(color.red)")
print("color.green is \(color.green)")
print("color.blue is \(color.blue)")