“线程1:致命错误:展开一个可选值时意外发现为零” swift

时间:2019-05-12 18:58:03

标签: swift error-handling optional-values

我对快速编码很陌生。

我在下面的代码中收到错误“线程1:致命错误:在展开可选值时意外发现nil”。有人知道如何解决此错误吗?

我有点理解可选的概念,但是对于如何实际使用它仍然很困惑,所以我猜了些什么放在哪里?和!。

我知道有很多类似的问题,但是我不明白如何在代码中应用该概念。

非常感谢所有帮助! :)

ITEM模型

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

struct Item {

var title : String
var done : Bool
var timeStamp : Date

var dictionary : [String:Any] {
    return [
    "title" : title,
    "done" : done,
    "timeStamp" : timeStamp
    ]
}


}

extension Item : DocumentSerializable {
init?(dictionary: [String:Any]) {
    guard let title = dictionary["title"] as? String,
        let done = dictionary["done"] as? Bool,
        let timeStamp = dictionary ["timeStamp"] as? Date else {return nil}

        self.init(title: title, done: done, timeStamp: timeStamp)
}
}

保存数据以保存

    @IBAction func addItemsButtonPressed(_ sender: AnyObject) {

    guard let title = addItemTextField.text, !title.isEmpty else { return }

    let newTask = Item(title: title, done: false, timeStamp: Date())


   var ref : DocumentReference? = nil
   ref = self.db.collection("tasks").addDocument(data: newTask.dictionary)
    { err in
        if let err = err {
            print("Error writing document: \(err)")
        } else {
            print("Document successfully written\(ref!.documentID)!")
        }
    }

    addItemTextField.endEditing(true)

    self.listTableView.reloadData()


        self.addItemTextField.isEnabled = true
        self.addItemsButton.isEnabled = true
        // clear textfield from old text
        self.addItemTextField.text = ""

}

加载数据

 func loadData() {

    db.collection("tasks").getDocuments() {
        querySnapshot, error in
        if let error = error {
            print("Error loading data")
        } else {
            self.itemArray = querySnapshot!.documents.flatMap({Item(dictionary: $0.data())})
            DispatchQueue.main.async {
                self.listTableView.reloadData()
            }
        }
    }


}

这是我得到错误的地方

func checkForUpdates () {

    db.collection("tasks").whereField("timeStamp", isGreaterThan: Date())
        .addSnapshotListener {
            querySnapshot, error in

            guard let snapshot = querySnapshot else {return}
            snapshot.documentChanges.forEach {
                diff in

                if diff.type == .added {

                //error on the line below
                self.itemArray.append(Item(dictionary: diff.document.data())!)
                    DispatchQueue.main.async {
                        self.listTableView.reloadData()
                    }
                }
            }
    }
}

0 个答案:

没有答案