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

前端 未结 4 2041
说谎
说谎 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:38

    The answer is no, it's not possible with the current specification.

    I wanted to do something similar. The best I could come up with was to use reflection in a function at the end of init(...). At least this way you can annotate your types and only add a single function call in init().

    
    fileprivate protocol BindableObjectPropertySettable {
        var didSet: () -> Void { get set }
    }
    
    @propertyDelegate
    class BindableObjectProperty: BindableObjectPropertySettable {
        var value: T {
            didSet {
                self.didSet()
            }
        }
        var didSet: () -> Void = { }
        init(initialValue: T) {
            self.value = initialValue
        }
    }
    
    extension BindableObject {
        // Call this at the end of init() after calling super
        func bindProperties(_ didSet: @escaping () -> Void) {
            let mirror = Mirror(reflecting: self)
            for child in mirror.children {
                if var child = child.value as? BindableObjectPropertySettable {
                    child.didSet = didSet
                }
            }
        }
    }
    

提交回复
热议问题