Handling fatal error: unexpectedly found nil while unwrapping an Optional value when creating a date object from a date string

Handling fatal error: unexpectedly found nil while unwrapping an Optional value when creating a date object from a date string

创建日期对象时出现奇怪的错误。

错误是"fatal error: unexpectedly found nil while unwrapping an Optional value"

显示问题的简化代码是

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 ) ;

打印时的数据对象是

{
    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 是来自 EKEventStore 的日历对象

奇怪的是代码可以在另一台设备上运行。

关于如何处理和解决的任何想法"fatal error: unexpectedly found nil while unwrapping an Optional value"?

NSDateFormatterdateFromString returns 可选 NSDate。您的 let startDate:NSDate! 声明 startDate 永远不会为 nil,但 dateFromString 返回 nil。

dateFromString 返回nil 的原因是您的日期格式字符串错误。按照评论中 Leo 的建议尝试 "yyyy-MM-dd HH:mm:ss",并考虑将 startDate 设为可选的 NSDate,只有在 non-nil.

时才展开它