加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 必须初始化类实例的所有存储属性,然后才能从初始化程序

发布时间:2020-12-14 04:43:56 所属栏目:百科 来源:网络整理
导读:我正在尝试在类中使用此代码,但我继续获取上述消息. let filePath: NSString! let _fileHandle: NSFileHandle! let _totalFileLength: CUnsignedLongLong!init?(filePath: String){ if let fileHandle = NSFileHandle(forReadingAtPath: filePath) { self.fi
我正在尝试在类中使用此代码,但我继续获取上述消息.

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可能会有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读