3

I don't understand why this is crashing. I'm using ios14 and XCode 12.0 beta 4. If I delete the DatePicker it works right. Any ideas?

struct MyView: View {
    
    @State private var myDate: Date?
    
    var body: some View {
        Form {
            if let selection = Binding<Date>($myDate) {
                DatePicker("myDate", selection: selection)
                Button("Delete myDate") {
                    myDate = nil
                }
            } else {
                Button("Add myDate") {
                    myDate = Date()
                }
            }
        }
    }
}
Lorenzo Fiamingo
  • 3,251
  • 2
  • 17
  • 35
  • 2
    Does this answer your question? [SwiftUI DatePicker Binding optional Date, valid nil](https://stackoverflow.com/questions/59272801/swiftui-datepicker-binding-optional-date-valid-nil) – TimTIM Wong Aug 21 '20 at 10:28

1 Answers1

0

This is actually very strange...

Binding<Date>($myDate) returns a binding with a date set to "Jan 1, 2001 at 1:00 AM".

This behavior seems to happen when the State is a Date (with a String, it returns nil as expected):

struct A {
    @State var date: Date? = nil
    @State var str: String? = nil

    var dateBinding: Binding<Date>? {
        Binding($date)
    }

    var stringBinding: Binding<String>? {
        Binding($str)
    }
}

A().dateBinding // not nil
A().dateBinding!.wrappedValue // "Jan 1, 2001 at 1:00 AM"

A().stringBinding // nil

And it seems to work fine without using property wrappers:

let stateDate = State<Date?>(initialValue: nil)
Binding<Date>(stateDate.projectedValue) // nil

This is probably an issue of Xcode 12 beta.

Edit:

This seems to be related to the state alone:

struct A {
    @State var date1: Date? = nil
}
A().date1 // Jan 1, 2001 at 1:00 AM"

State<Date?>(initialValue: nil).wrappedValue // nil
rraphael
  • 10,041
  • 2
  • 25
  • 33