Skip to content

Instantly share code, notes, and snippets.

@keybuk
Last active June 7, 2019 00:35
Show Gist options
  • Save keybuk/851a77cde856a8c2ab74b24d57bbd511 to your computer and use it in GitHub Desktop.
Save keybuk/851a77cde856a8c2ab74b24d57bbd511 to your computer and use it in GitHub Desktop.
Homebrew binding and state to understand how it works
@propertyDelegate
public struct Binding<Value> {
public var value: Value {
get { getValue() }
nonmutating set { setValue(newValue) }
}
public init(getValue: @escaping () -> Value, setValue: @escaping (Value) -> Void) {
self.getValue = getValue
self.setValue = setValue
}
private let getValue: () -> Value
private let setValue: (Value) -> Void
}
private class Storage<Value> {
var value: Value
init(initialValue value: Value) {
self.value = value
}
}
@propertyDelegate
public struct State<Value> {
private let storage: Storage<Value>
public var value: Value {
get { storage.value }
nonmutating set { storage.value = newValue }
}
public init(initialValue value: Value) {
storage = Storage(initialValue: value)
}
public var binding: Binding<Value> {
Binding(getValue: { self.value }, setValue: { self.value = $0 })
}
public var delegateValue: Binding<Value> { binding }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment