美文网首页
swift @propertyWrapper的使用

swift @propertyWrapper的使用

作者: 迷路的小小 | 来源:发表于2022-02-28 11:38 被阅读0次
    @propertyWrapper
    struct Map {
        private var value: String = "123"
        
        var wrappedValue: String {
            get {
                return value
            }
            set {
                value = newValue
            }
        }
        
        var projectedValue: Int? {
            Int(value)
        }
        
       static subscript<EnclosingSelf: AnyObject>(
            _enclosingInstance object: EnclosingSelf,
            wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, String>,
            storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Map>
        ) -> 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<EnclosingSelf: AnyObject>( _enclosingInstance object: EnclosingSelf, wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, String>, storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Map> ) -> String
      1. EnclosingSelf可以不是AnyObject,但如此只能使用get属性,同时wrappedValue也只能是可读属性。
      2. 标签_enclosingInstancewrappedstorage不可改变,否则无效

    相关文章

      网友评论

          本文标题:swift @propertyWrapper的使用

          本文链接:https://www.haomeiwen.com/subject/tlllrrtx.html