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
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
Initializers are called to create a new instance of a particular type. In its simplest form, an initializer is like an instance method with no parameters, written using the init keyword: init() {
The init() initializer for Bicycle starts by calling super. init(), which calls the default initializer for the Bicycle class's superclass, Vehicle. This ensures that the numberOfWheels inherited property is initialized by Vehicle before Bicycle has the opportunity to modify the property.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With