Search code examples
iosswiftdictionarytimedateformatter

Swift : Map function found nil while unwrapping an Optional value


I'm trying to compare times, following this link, but it crashes on me. I have literally the same codes but it keeps crashing on the dateComponents line or the sorted() line depending on where I put the function.

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...
}

ERROR:

[]
fatal error: unexpectedly found nil while unwrapping an Optional value

If I pass in an array or hardcode an array in the function it still crashes.


Solution

  • The crash that you are getting is due to difference in the format for passed value and format used in date formatter.

    formatter.dateFormat = "h: mm a"
    

    While your formatter uses space between 'h:' and 'mm' and you may have passed data as below. ( without the space between 4: and 30 in 4:30 AM

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

    Date formatter will not return valid date and you have used '!' operator which result in crash.

    Either you can change the date-format or pass data according to format. This will solve the issue and you will get

    • This is timemap

    [hour: 4 minute: 30 isLeapMonth: false , hour: 13 minute: 0 isLeapMonth: false , hour: 15 minute: 20 isLeapMonth: false , hour: 18 minute: 40 isLeapMonth: false , hour: 21 minute: 10 isLeapMonth: false ]

    • This is next date

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

    • This is upcoming date

    [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]