Gerard G
Gerard G

Reputation: 3463

All stored properties of a class instance must be initialized before returning nil from an initializer

I'm trying to use this code in a class though I keep on getting the above message.

    let filePath: NSString!
    let _fileHandle: NSFileHandle!
    let _totalFileLength: CUnsignedLongLong!




init?(filePath: String)
{


    if let fileHandle = NSFileHandle(forReadingAtPath: filePath)
    {

        self.filePath = filePath
        self._fileHandle = NSFileHandle(forReadingAtPath: filePath)
        self._totalFileLength = self._fileHandle.seekToEndOfFile()
    }
    else
    {

        return nil  //The error is on this line
    }
}

How do fix this so I don't get this error:

All stored properties of a class instance must be initialized before returning nil from an initializer

Upvotes: 5

Views: 3225

Answers (1)

Eric Aya
Eric Aya

Reputation: 70113

You can make it work with variables and a call to super.init() (for creating self before accessing its properties):

class Test: NSObject {
    var filePath: NSString!
    var _fileHandle: NSFileHandle!
    var _totalFileLength: CUnsignedLongLong!

    init?(filePath: String) {
        super.init()
        if let fileHandle = NSFileHandle(forReadingAtPath: filePath)
        {
            self.filePath = filePath
            self._fileHandle = NSFileHandle(forReadingAtPath: filePath)
            self._totalFileLength = self._fileHandle.seekToEndOfFile()
        }
        else
        {
            return nil
        }
    }
}

But if you plan to stick to your version with constants, then it's out of my comfort zone, and maybe this answer could be of help.

Upvotes: 7

Related Questions