gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:07:24 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com