Last active
August 13, 2020 19:38
-
-
Save danielctull/485a78a3c61433c76d31533798bfa275 to your computer and use it in GitHub Desktop.
Implementing an invmap function on SwiftUI's Binding type.
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
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