Skip to content

Instantly share code, notes, and snippets.

@huynguyencong
Last active October 4, 2020 13:42
Show Gist options
  • Save huynguyencong/d4319baf27863ef89641315bee389062 to your computer and use it in GitHub Desktop.
Save huynguyencong/d4319baf27863ef89641315bee389062 to your computer and use it in GitHub Desktop.
Binding extensions:
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