Skip to content

Instantly share code, notes, and snippets.

@josippetric
Last active March 31, 2023 07:38
Show Gist options
  • Select an option

  • Save josippetric/da699cd8235d8f6860d57706a5ede2f7 to your computer and use it in GitHub Desktop.

Select an option

Save josippetric/da699cd8235d8f6860d57706a5ede2f7 to your computer and use it in GitHub Desktop.
SwiftUI Helpers
import SwiftUI
// Overload that allows some bindings to be optional. E.g. having an optional
// property bound to the TextField
// TextField("", text: $optionalProperty ?? "default value")
func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
Binding(
get: { lhs.wrappedValue ?? rhs },
set: { lhs.wrappedValue = $0 }
)
}
//// BINDING EXTENSION
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
Binding(
get: { self.wrappedValue },
set: { newValue in
self.wrappedValue = newValue
handler(newValue)
}
)
}
}
// Example usage of onChange extension
TextField("Your name:", text: $name.onChange(nameChanged)
func nameChanged(to newValue: String) {
// Do something when name has been changed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment