从初始化器返回nil之前,必须初始化类实例的所有存储属性. [英] All stored properties of a class instance must be initialized before returning nil from an initializer
本文介绍了从初始化器返回nil之前,必须初始化类实例的所有存储属性.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尽管我不断收到上述消息,但我仍试图在一个类中使用此代码.
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:
类实例的所有存储属性必须在初始化之前 从初始化程序返回nil
All stored properties of a class instance must be initialized before returning nil from an initializer
推荐答案
您可以使其与变量和对super.init()
的调用一起使用(用于在访问其属性之前创建self
):
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.
这篇关于从初始化器返回nil之前,必须初始化类实例的所有存储属性.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文