Last active
April 23, 2020 19:27
-
-
Save IanKeen/2a6a90e0bb46ed24886c446db2f3d829 to your computer and use it in GitHub Desktop.
PropertyWrapper: Derived properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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