Sammy Sammy - 6 months ago 63
Swift Question

Getting nil values using NSDate (fatal error: unexpectedly found nil while unwrapping an Optional value)

I'm new to iOS dev and getting the error:


fatal error: unexpectedly found nil while unwrapping an Optional value


The value at the bottom of xCode for self (NSDate) is correct but dateStringFormatter and d are showing the memory address instead of a value, and dateString remains unchanged. Any ideas? I had this code working earlier and have been trying to fix it after a bad commit, so I'm thinking maybe something to do with storyboard / something that wouldn't show up in code?
Here's the code:

extension NSDate{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "hh:mm"
dateStringFormatter.locale = NSLocale(localeIdentifier:
"en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
}
}

class EditViewController: UIViewController, UITableViewDelegate,
NSFetchedResultsControllerDelegate {
........
@IBAction func btnSetDate(sender: UIButton) {
let newDate = NSDate(dateString: "10-33")
StartDatePicker.date = newDate
}
}


Thanks!

Answer

You either changed the date string literal or the format. Make one of the following changes:

let newDate = NSDate(dateString: "10:33")
// or
dateStringFormatter.dateFormat = "hh-mm"