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

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

虽然我不断收到上述消息,但我正在尝试在 class 中使用此代码。

    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
    }
}

如何解决这个问题,这样我就不会收到这个错误:

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

您可以使用变量和调用 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 可能会有所帮助。