Skip to content

Instantly share code, notes, and snippets.

@danielctull
Last active August 13, 2020 19:38
Show Gist options
  • Save danielctull/485a78a3c61433c76d31533798bfa275 to your computer and use it in GitHub Desktop.
Save danielctull/485a78a3c61433c76d31533798bfa275 to your computer and use it in GitHub Desktop.
Implementing an invmap function on SwiftUI's Binding type.
import SwiftUI
extension Binding {
func invmap<NewValue>(
to: @escaping (Value) -> NewValue,
from: @escaping (NewValue) -> Value
) -> Binding<NewValue> {
Binding<NewValue>(
get: { to(wrappedValue) },
set: { wrappedValue = from($0) }
)
}
}
var tuple: (Int, String) = (1, "A")
let tupleBinding = Binding(get: { tuple }, set: { tuple = $0 })
struct Foo {
let int: Int
let string: String
}
let fooBinding = tupleBinding.invmap(to: Foo.init,
from: { ($0.int, $0.string) })
print("Before", tuple)
fooBinding.wrappedValue = Foo(int: 2, string: "B")
print("After", tuple)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment