I have the following NSDate extension initializer to create a NSDate object from a given string.
extension NSDate {
convenience init(string: String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateStringFormatter.dateFromString(string)
self.init(timeInterval:0, sinceDate:date!)
}
}
But the call to self.init method force unwraps the date variable which is not safe. So I'm trying to make this a failable initializer.
extension NSDate {
convenience init?(string: String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let date = dateStringFormatter.dateFromString(string) else {
return nil
}
self.init(timeInterval:0, sinceDate:date)
}
}
But it crashes with a EXC_BAD_ACCESS error at the nil returning line. I can't figure out why.
What am I doing something wrong here?
If you use
extensionyou need to initialize the "superclass" before returning nil. SeeThe docs states