1

I got a strange error when creating a date object.

The error is "fatal error: unexpectedly found nil while unwrapping an Optional value"

Simplified code that shows the issue is

let dateFormatter = NSDateFormatter() ;
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" ;

let startDateText:String = (data["startDate"] as AnyObject? as? String) ?? "";      

print( startDateText ) ;
let startDate:NSDate! = dateFormatter.dateFromString(startDateText) ;
print( startDate ) ;

The data object when printed is

{
    calendar = archived;
    endDate = "2016-01-25 15:15:00";
    notes = "notes and something";
    startDate = "2016-01-25 14:00:00";
    title = "First event from the command line";
}

Archived is a calendar object from EKEventStore

The strange part is the code works on another device.

Any ideas on how to handle and solve "fatal error: unexpectedly found nil while unwrapping an Optional value"?

JAL
  • 41,701
  • 23
  • 172
  • 300
Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64

1 Answers1

4

NSDateFormatter's dateFromString returns an optional NSDate. Your let startDate:NSDate! states that startDate will never be nil, but dateFromString is returning nil.

The reason why dateFromString is returning nil is because your date format string is wrong. Try "yyyy-MM-dd HH:mm:ss" as Leo suggested in the comments, and consider making startDate an optional NSDate, only unwrapping it if it is non-nil.

JAL
  • 41,701
  • 23
  • 172
  • 300