【发布时间】:2017-10-01 08:59:32
【问题描述】:
我正在尝试比较时间,遵循这个link,但它在我身上崩溃了。我实际上有相同的代码,但它总是在dateComponents 行或sorted() 行上崩溃,具体取决于我放置函数的位置。
func setCurrentTime(times: [String]) {
let formatter = DateFormatter()
formatter.dateFormat = "h: mm a"
let timeMap = times.map {
Calendar.current.dateComponents([.hour, .minute], from: formatter.date(from: $0)!)
} // Crashes here ...
let upcomingTIme = timeMap.map {
Calendar.current.nextDate(after: Date(), matching: $0, matchingPolicy: .nextTime)!
}
print(upcomingTime) // Returns []
let nextTime = upcomingTIme.sorted().first! // Crashes here too, error line shown below
print(nextTime) // Doesn't get printed...
}
错误:
[]
fatal error: unexpectedly found nil while unwrapping an Optional value
如果我在函数中传入一个数组或硬编码一个数组,它仍然会崩溃。
【问题讨论】:
-
日期格式应为“h:mm a”
-
Tthe dateformatter 无法使用您给定的格式解析输入,因此它返回
nil并且因为您强制解包结果,所以您会崩溃。如果您修复格式字符串,它可能会起作用,但使用flatmap过滤选项并避免强制展开更具防御性 -
您能提一下通过的
[String]是什么吗?会更清楚...
标签: ios swift dictionary time dateformatter