Last active
June 7, 2019 00:35
-
-
Save keybuk/851a77cde856a8c2ab74b24d57bbd511 to your computer and use it in GitHub Desktop.
Homebrew binding and state to understand how it works
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
@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