Thats seems like a good solution if you don't want to add unwrapped properties to an extension on your NSManagedObject
, like this:
extension MyObject {
var wrappedDate: Date {
date ?? Date()
}
}
I would, however, extract the Binding
to a computed property like this:
var dateSelection: Binding<Date> {
Binding {
myObject.date ?? Date()
} set {
myObject.date = newValue
}
}
You could create a property in the view that binds to the DatePicker
, and on view initailisation and dismissal, connect that back to the NSManagedObject
property. For example:
@State private var dateSelection: Date
...
init() {
_dateSelection = State(wrappedValue: myObject.date ?? Date())
}
...
.onDisappear {
myObject.date = dateSelection // do wherever suits you
}
Personally, I do a combination of the first and third, but it's up to you how you do it.