ios - swift : Map function found nil while unwrapping an Optional value

标签 ios swift dictionary time dateformatter

我正在尝试比较时间,遵循此 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

如果我在函数中传入一个数组或对一个数组进行硬编码,它仍然会崩溃。

最佳答案

您遇到的崩溃是由于传递值的格式与日期格式化程序中使用的格式不同所致。

formatter.dateFormat = "h: mm a"

虽然您的格式化程序使用 'h:''mm' 之间的空格,但您可能传递了如下数据。 (凌晨 4:30 的 4: 和 30 之间没有空格

let times = ["4:30 AM","1:00 PM","3:20 PM","6:40 PM","9:10 PM"] 

日期格式化程序不会返回有效日期,并且您使用了“!”导致崩溃的运算符(operator)。

您可以更改日期格式或根据格式传递数据。这将解决问题,您将得到

  • 这是时间表

[小时: 4 分钟: 30 isLeapMonth: false , 小时: 13 分钟: 0 isLeapMonth: false , 小时: 15 分钟: 20 isLeapMonth: false , 小时: 18 分钟: 40 isLeapMonth: false , 小时: 21 分钟: 10 isLeapMonth: false ]

  • 这是下一个日期

2017-10-01 13:10:00 +0000

  • 这是即将到来的日期

[2017-10-01 23:00:00 +0000, 2017-10-02 07:30:00 +0000, 2017-10-02 09:50:00 +0000, 2017-10-01 13: 10:00 +0000, 2017-10-01 15:40:00 +0000]

关于ios - swift : Map function found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510806/

相关文章:

iphone - 在 iOS 中保存和加载设置以及游戏进度

ios - 您如何使用 Alamofire 测试证书固定?

c# - 字典枚举关键性能

python - 迭代字典(字典内)来总结排名

ios - TableView 不滚动且单元格未启用

ios - 加速度计的性能问题

iOS:从 SQLite 数据库填充 tableView

ios - SwiftUI EditButton() 错误

ios - 在通知扩展中单击通信按钮

python - 检查Python中连续相等元素的数量