SwiftUI-属性包装器介绍

2023-04-06  本文已影响0人  xiaofu666

属性包装器就是对属性的get和set方法经过包装处理,例如我们实现一个MyColor结构体,允许用户传入R,G,B三种颜色的值,但是RGB的值是限定在0-255之间,如何防范用户传入错误的值呢,此时我们可以实现自定义属性包装器,对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)")
上一篇 下一篇

猜你喜欢

热点阅读