SwiftUI-属性包装器介绍

属性包装器就是对属性的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)")
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容