swift @propertyWrapper的使用

@propertyWrapper
struct Map {
    private var value: String = "123"
    
    var wrappedValue: String {
        get {
            return value
        }
        set {
            value = newValue
        }
    }
    
    var projectedValue: Int? {
        Int(value)
    }
    
   static subscript(
        _enclosingInstance object: EnclosingSelf,
        wrapped wrappedKeyPath: ReferenceWritableKeyPath,
        storage storageKeyPath: ReferenceWritableKeyPath
    ) -> String {
        get {
            object[keyPath: storageKeyPath].value
        }
        set {
            object[keyPath: storageKeyPath].value = newValue
            print(newValue, "------")
        }
        // TODO: Benchmark and explore a possibility to use _modify
    }
}
var text = Text()
test.mothds = "20"
// 20 ------
  • projectedValue启用$语法糖
  • 函数static subscript( _enclosingInstance object: EnclosingSelf, wrapped wrappedKeyPath: ReferenceWritableKeyPath, storage storageKeyPath: ReferenceWritableKeyPath ) -> String
    1. EnclosingSelf可以不是AnyObject,但如此只能使用get属性,同时wrappedValue也只能是可读属性。
    2. 标签_enclosingInstancewrappedstorage不可改变,否则无效

你可能感兴趣的:(swift @propertyWrapper的使用)