Optional Type Date

I'm sorry I know this is basic swift, but how do I get I make the selection an optional return? I know it's with ?? "" with a string, but I don't know how to do it with a date type.

Also how do I get a navigationBarTitle to work on this view? The "My Calendar" doesn't show up when I run the code.

import SwiftUI

struct ReciPrep: View {
    @State private var date: Date? = ni
    @Environment(\.calendar) var calendar
    
    @State private var showingAddView = false
    var body: some View {
        VStack{
            DatePicker("Calendar", selection: $date, in: Date.now...,displayedComponents: [.date]) //Error: Cannot convert value of type 'Binding<Date?>' to expected argument type 'Binding<Date>'
                .datePickerStyle(.graphical)
            Spacer()
        }
        .navigationBarTitle("My Calendar")
    }
}

Any help would be greatly appreciated. Have a good day!

I want date to be nil if no date is selected. How do I do that in the DatePicker?

You cannot do it directly.

You should try (but I have not completed this yet) to:

  • create a var to hold the current date value
  • when picker closes (onDisappear), perform code to test if data has changed
  • do what you need then.

But calling .onDisappear on DatePicker is not that easy: https://stackoverflow.com/questions/66190299/swiftui-datepicker-events

If that does not work, you may try with onChange:

  • declare an optional date:
    @State private var newDate : Date? = nil
  • Call .onChange modifier on picker
        DatePicker(
            "Start Date",
            selection: $date,
            displayedComponents: [.date]
        )
            .onChange(of: date, perform: { value in
                newDate = date  // Do whatever you need then
                print("changed", value, newDate)
            })
Optional Type Date
 
 
Q