Nathan McKaskle
Nathan McKaskle

Reputation: 3063

Swift 2.1 DatePicker NSDate Error Nil Unwrapping Optional Value?

I have a class that I'm trying to set a begin and end date in:

class Dates {
    var beginDateTime = NSDate()
    var endDateTime = NSDate()    
}

And in my View Controller I create an instance of it:

var dates: Dates!

I also have two date pickers:

@IBOutlet weak var datePicker1: UIDatePicker!
@IBOutlet weak var datePicker2: UIDatePicker!

Then when trying to set these times in a navigation segue...

dates.beginDateTime = datePicker1.date
dates.endDateTime = datePicker2.date

I get:

fatal error: unexpectedly found nil while unwrapping an Optional value

There's no optional value here... I don't understand. The dates are set. Why am I getting this error? There are no nil values here. I even tested them in a print(datePicker1.date) command, they're set for sure.

In fact I have additional code in a function here to programmatically set the dates for the user on viewDidLoad, which works fine:

func setDatePicker(datePicker: UIDatePicker) {
    datePicker.minimumDate = NSDate()
    let calendar:NSCalendar = NSCalendar.currentCalendar()
    let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: NSDate())
    if count > 0 {
        components.hour = 23
        components.minute = 30
    } else {
        components.hour = 19
        components.minute = 00
    }
    let date = calendar.dateFromComponents(components)!
    datePicker.setDate(date, animated: true)
    count++
}

Upvotes: 0

Views: 823

Answers (1)

Vishnu gondlekar
Vishnu gondlekar

Reputation: 3956

Dates are set in your date picker but your dates object is probably nil. You have just declared the dates object, so unless you allocate memory and initialise it, it will be nil. Do

var dates = Dates()

That will fix that error

Upvotes: 1

Related Questions