【问题标题】:How to rectify the error of "self' used before 'self.init' call or assignment to 'self'"?如何纠正“self.init”调用或分配给“self”之前使用的“self”错误?
【发布时间】:2019-08-30 01:20:28
【问题描述】:

我面临selfself.init 调用或分配给self 之前在tableview 单元格项目的模型类的以下代码中使用的错误,它发生在我尝试获取表格的文档ID 之后单元格项目。

应该怎么做?请推荐。

import Foundation
import Firebase
import FirebaseFirestore


protocol DocumentSerializable  {
    init?(dictionary:[String:Any])
}


struct Post {
    var _postKey:  String!

     var _username: String!
     var _postTitle: String!
     var _postcategory:  String!
     var _postContent:  String!




    var dictionary:[String:Any] {
        return [
            "username": _username,
            "postTitle":_postTitle,
            "postcategory":_postcategory,
            "postContent":_postContent,
            "postKey":_postKey
        ]
    }

}

extension Post : DocumentSerializable {



    init?(dictionary: [String : Any]) {

        guard let postKey = key,
            let username = dictionary["username"] as? String,

            let postTitle = dictionary["postTitle"] as? String,
            let postcategory = dictionary["postcategory"] as? String,
            let postContent = dictionary["postContent"] as? String   else { return nil }


        self.init(_postKey: postKey, _username: username ,_postTitle: postTitle, _postcategory: postcategory, _postContent: postContent)
    }
}

【问题讨论】:

  • 我想你的意思是guard let postKey = dictionary["postKey"] as? String
  • 但是我还需要获取documentID,会怎样?
  • documentID postKey,不是吗?
  • 不,那不正确,所以我编辑了它
  • key 来自哪里?你为什么使用 _ 前缀?为什么你的 struct 属性隐式地解包了可选项?

标签: ios swift firebase model google-cloud-firestore


【解决方案1】:

你有一些循环依赖,要访问字典变量你需要一个实例,要创建实例你需要调用 init 但再次调用 init 你应该初始化字典变量等等。您可以将字典变量设为静态。

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多