我正在尝试在类中使用此代码,但我继续收到上述消息。
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
}
}
如何修复此问题,以免出现此错误:
之前必须初始化类实例的所有存储属性 从初始化程序返回nil
答案 0 :(得分:7)
您可以使用变量和super.init()
调用(用于在访问其属性之前创建self
):
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
}
}
}
但是如果你打算坚持使用常量的版本,那么它就会超出我的舒适区域,也许this answer可能有所帮助。