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

1

5

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

Astronavigation answered 10/4, 2015 at 4:25 Comment(0)
W
7

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.

Wingfield answered 10/4, 2015 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.