Last active
October 4, 2020 13:42
-
-
Save huynguyencong/d4319baf27863ef89641315bee389062 to your computer and use it in GitHub Desktop.
Binding extensions:
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 map<MappedValue>( | |
valueToMappedValue: @escaping (Value) -> MappedValue, | |
mappedValueToValue: @escaping (MappedValue) -> Value | |
) -> Binding<MappedValue> { | |
Binding<MappedValue>.init { () -> MappedValue in | |
return valueToMappedValue(wrappedValue) | |
} set: { mappedValue in | |
wrappedValue = mappedValueToValue(mappedValue) | |
} | |
} | |
func onSet(_ action: @escaping (Value) -> Void) -> Binding<Value> { | |
return Binding { () -> Value in | |
return wrappedValue | |
} set: { value in | |
action(value) | |
wrappedValue = value | |
} | |
} | |
} | |
func ??<T>(binding: Binding<T?>, fallback: T) -> Binding<T> { | |
return Binding(get: { | |
binding.wrappedValue ?? fallback | |
}, set: { | |
binding.wrappedValue = $0 | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment