Reputation: 358
I have a core-data database with many date-fields. But not all of them always have to be filled. e.g. "died on" can't be filled, as log as the person is still alive or "terminated on" as long as the person is still working.
So how can I set a) the value of an date-attribute to nil b) use it inside a date-picker?
@State private var birthDate = Date()
[...]
DatePicker(selection: $birthDate, displayedComponents: [.date], label: { Text("birthDate") })
.padding(.leading, 0.0)
.frame(width: 120.0)
.labelsHidden()
I can set
@State private var birtDate: Date? = nil
but in this case, the DatePicker will moan.
Upvotes: 1
Views: 162
Reputation: 257749
The DatePicker
requires (!) non-optional selection, so we can map it to core-data object property using calculable proxy binding.
Assuming we have person
as core-data object (they are observable by default) it can be as follows:
@ObservedObject var person: Person
// ...
DatePicker(selection:
Binding(get: { person.diedOn ?? Date() }, set: { person.diedOn = $0 }) // << !!
, displayedComponents: [.date], label: { Text("birthDate") })
or that Binding can be moved into helper calculable property or local in-body var - that is just styling, not important.
Upvotes: 1