Can a Swift Property Wrapper reference the owner of the property its wrapping?

前端 未结 4 2026
说谎
说谎 2021-02-07 01:00

From within a property wrapper in Swift, can you someone refer back to the instance of the class or struck that owns the property being wrapped? Using self doesn\'t

4条回答
  •  醉梦人生
    2021-02-07 01:44

    My experiments based on : https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md#referencing-the-enclosing-self-in-a-wrapper-type

    protocol Observer: AnyObject {
        func observableValueDidChange(newValue: T)
    }
    
    @propertyWrapper
    public struct Observable {
        public var stored: T
        weak var observer: Observer?
    
        init(wrappedValue: T, observer: Observer?) {
            self.stored = wrappedValue
        }
    
        public var wrappedValue: T {
            get { return stored }
            set {
                if newValue != stored {
                    observer?.observableValueDidChange(newValue: newValue)
                }
                stored = newValue
            }
        }
    }
    
    class testClass: Observer {
        @Observable(observer: nil) var some: Int = 2
    
        func observableValueDidChange(newValue: T) {
            print("lol")
        }
    
        init(){
            _some.observer = self
        }
    }
    
    let a = testClass()
    
    a.some = 4
    a.some = 6
    

提交回复
热议问题