Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created March 10, 2023 14:46
Show Gist options
  • Save shaps80/7fedbefaf506c391a567bf738fe10cfb to your computer and use it in GitHub Desktop.
Save shaps80/7fedbefaf506c391a567bf738fe10cfb to your computer and use it in GitHub Desktop.
Convert SwiftUI Optional Binding to Non-Optional Binding
extension Binding {
public init(wrappedValue: Binding<Value?>, defaultValue: Value) {
self = Binding<Value>(
get: { wrappedValue.wrappedValue ?? defaultValue },
set: { wrappedValue.wrappedValue = $0 }
)
}
public func defaultValue<T>(_ value: T) -> Binding<T> where Value == T? {
Binding<T>(
get: { wrappedValue ?? value },
set: { wrappedValue = $0 }
)
}
}
@shaps80
Copy link
Author

shaps80 commented Mar 10, 2023

Usage:

@Binding private var name: String?
// …
TextField(“”, text: $name.defaultValue(“”))

Particularly useful when dealing with CoreData objects:

@ObservedObject var model: Model
TextField(“”, text: $model.name.defaultValue(“”))

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