Failable initializer for convenience init fails

936 Views Asked by At

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?

1

There are 1 best solutions below

4
Code On

If you use extension you need to initialize the "superclass" before returning nil. See

convenience init?(string: String) {
    let dateStringFormatter = NSDateFormatter()
    dateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    guard let date = dateStringFormatter.dateFromString(string) else {
        self.init()
        return nil
    }

    self.init(timeInterval:0, sinceDate:date)
}

The docs states

All of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization.