我正在尝试按照此链接比较时间,但它在我身上崩溃了。我实际上有相同的代码,但它会一直在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
如果我在函数中传入一个数组或硬编码一个数组,它仍然会崩溃。