Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Last active March 24, 2025 17:04
Show Gist options
  • Save StewartLynch/8a4511d6f3525a55fcfe6fb005566f16 to your computer and use it in GitHub Desktop.
Save StewartLynch/8a4511d6f3525a55fcfe6fb005566f16 to your computer and use it in GitHub Desktop.
Optional Binding
import SwiftUI
extension Binding {
/// Binding to an optional value by providing a defatult value.
///
/// example
///
/// struct Sample: View {
/// @Binding var name: String?
///
/// var body: some View {
/// TextField("Name", text: .init($name, defaultValue: ""))
/// }
/// }
/// Creates a Binding<Value>' for an optional value with a default.
/// - Parameters:
/// - optionalBinding: A binding to an optional value.
/// - defaultValue: The default value to use when the optional is nil'.
///
init(_ optionalBinding: Binding<Value?>, defaultValue: Value) where Value: Sendable {
self.init(
get: {optionalBinding.wrappedValue ?? defaultValue},
set: {newValue in
optionalBinding.wrappedValue = newValue
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment