0

I have a class that is constructed with NSData, and I would like to construct a convenience init that reads the NSData from a file. Naturally, that might fail, so the convenience init must be an init?, but I can't see how to construct it. What I've tried is

convenience init?(path: String, encoding: NSStringEncoding) {
    if let data = NSData(contentsOfFile: path) {
        self.init(data: data, encoding: encoding)
    } else {
        return nil
    }
}

but I get the error "All stored properties of a class must be initialized before returning nil from an initializer". It seems pointless to set up all of the properties to dummy values and then just return nil. What am I missing?

Grimxn
  • 22,115
  • 10
  • 72
  • 85
  • 2
    That's a known issue and has been discussed before, e.g. here: [Best practice to implement a failable initializer in swift](http://stackoverflow.com/questions/26495586/best-practice-to-implement-a-failable-initializer-in-swift). – Martin R Apr 10 '15 at 10:17
  • Many thanks for that, @MartinR. I had searched for it, but hadn't seen that answer. – Grimxn Apr 10 '15 at 10:19

0 Answers0