Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created November 10, 2022 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmlongco/2fe49fd5e458955ec21bfa8d914c1a42 to your computer and use it in GitHub Desktop.
Save hmlongco/2fe49fd5e458955ec21bfa8d914c1a42 to your computer and use it in GitHub Desktop.
Binding+defaultValue
extension Binding {
public func defaultValue<T>(_ value: T) -> Binding<T> where Value == Optional<T> {
Binding<T> {
wrappedValue ?? value
} set: {
wrappedValue = $0
}
}
}
@hmlongco
Copy link
Author

struct OptionalView: View {
    @Binding var name: String?
    var body: some View {
        Textfield("Name", text: $name.defaultValue(""))
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment