Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Last active April 23, 2020 19:27
Show Gist options
  • Save IanKeen/2a6a90e0bb46ed24886c446db2f3d829 to your computer and use it in GitHub Desktop.
Save IanKeen/2a6a90e0bb46ed24886c446db2f3d829 to your computer and use it in GitHub Desktop.
PropertyWrapper: Derived properties
@propertyWrapper
struct Derived<Instance, Value> {
var wrappedValue: Value {
get { fatalError() }
set { fatalError() }
}
private let getter: (Instance) -> Value
private let setter: (Instance, Value) -> Void
init(_ keyPath: ReferenceWritableKeyPath<Instance, Value>) {
getter = { $0[keyPath: keyPath] }
setter = { $0[keyPath: keyPath] = $1 }
}
static subscript(
_enclosingInstance instance: Instance,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<Instance, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<Instance, Self>
) -> Value {
get { instance[keyPath: storageKeyPath].getter(instance) }
set { instance[keyPath: storageKeyPath].setter(instance, newValue) }
}
}
class Parent: UIView {
private let label = UILabel()
@Derived(\Parent.label.text) var text: String?
}
let instance = Parent()
instance.text // nil
instance.text = "foo"
instance.text // foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment