在从初始化程序返回nil之前,必须初始化类实例的所有存储属性

upl*_*com 5 swift xcode6.3

我正在尝试在类中使用此代码,但我继续获取上述消息.

    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
    }
}
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题,所以我没有得到这个错误:

在从初始化程序返回nil之前,必须初始化类实例的所有存储属性

aya*_*aio 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果你打算坚持你的版本与常量,那么它是我的舒适区,也许这个答案可能会有所帮助.