我使用错误的文档来构建 dateFormat 来解析以预定义格式出现的时间。maddy(下)提供了指向正确文档的链接。
以下是我使用错误格式时发生的情况:
var idf = DateFormatter()
idf.locale = Locale(identifier: "en_US")
idf.dateStyle = .none
idf.dateFormat = "hh:MM:SSa"
// Of the variables defined here, the only one that doesn't cause an error
// is the last one:
var sMidnight: String = "12:00:00AM"
var sEarly: String = "12:40:22AM"
var sMorning: String = "6:00:00AM"
var sNoon: String = "12:00:00PM"
var sAfternoon: String = "12:30:22PM"
var sEvening: String = "7:05:45PM"
// Put any of the variables besides sEvening here and you get a crash.
// "fatal error: unexpectedly found nil while unwrapping an Optional value"
var date: Date = idf.date(from: sEvening)!
print(idf.string(from: date)) // prints 07:05:45 PM