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

I am trying to use this code in a class, although I keep 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 to fix this, so I do not get this error:

All stored properties of the class instance must be initialized before returning zero from the initializer

+5
source share
1 answer

You can make it work with variables and call super.init() (to create 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 this is from my comfort zone and perhaps this answer may help.

+7
source

All Articles