Skip to content

Instantly share code, notes, and snippets.

@jasdev
Last active July 26, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/f4a56ee700576aebc57627c23f21c431 to your computer and use it in GitHub Desktop.
Save jasdev/f4a56ee700576aebc57627c23f21c431 to your computer and use it in GitHub Desktop.
Binding’s affordances.
import SwiftUI
extension Binding {
func zip(
_ other: Binding<Value>
) -> Binding<(Value, Value)> {
Binding<(Value, Value)>(
get: { (self.wrappedValue, other.wrappedValue) },
set: { pair in
self.wrappedValue = pair.0
other.wrappedValue = pair.1
}
)
}
}
func join<Value>(nested: Binding<Binding<Value>>) -> Binding<Value> {
Binding<Value>(
get: { nested.wrappedValue.wrappedValue },
set: { nested.wrappedValue.wrappedValue = $0 }
)
}
extension Binding {
func flatMap<TransformedValue>(
_ transform: WritableKeyPath<Value, Binding<TransformedValue>>
) -> Binding<TransformedValue> {
Binding<TransformedValue>(
get: { self.wrappedValue[keyPath: transform].wrappedValue },
set: { self.wrappedValue[keyPath: transform].wrappedValue = $0 }
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment