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

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

    The answer is yes! See this answer

    Example code for calling ObservableObject publisher with a UserDefaults wrapper:

    import Combine
    import Foundation
    
    class LocalSettings: ObservableObject {
      static var shared = LocalSettings()
    
      @Setting(key: "TabSelection")
      var tabSelection: Int = 0
    }
    
    @propertyWrapper
    struct Setting {
      private let key: String
      private let defaultValue: T
    
      init(wrappedValue value: T, key: String) {
        self.key = key
        self.defaultValue = value
      }
    
      var wrappedValue: T {
        get {
          UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
          UserDefaults.standard.set(newValue, forKey: key)
        }
      }
    
      public static subscript(
        _enclosingInstance object: EnclosingSelf,
        wrapped wrappedKeyPath: ReferenceWritableKeyPath,
        storage storageKeyPath: ReferenceWritableKeyPath>
      ) -> T {
        get {
          return object[keyPath: storageKeyPath].wrappedValue
        }
        set {
          (object.objectWillChange as? ObservableObjectPublisher)?.send()
          UserDefaults.standard.set(newValue, forKey: object[keyPath: storageKeyPath].key)
        }
      }
    }
    

提交回复
热议问题