在 swift 4.0 中从 Firebase 快照字典中获取值时解包可选的 nil



在 swift 4.0 中从 Firebase 快照字典中获取值时,我在解开可选的 nil 时遇到问题

这是我的代码

Database.database().reference().child("questionPosts").queryOrderedByKey().observe(.childAdded) { (snapshot) in
if let dict = snapshot.value as? NSDictionary {
//var questionName = dict["name"] as! String
//var created_by = dict["email"] as! String
let questionTitle = dict["name"] as? String
let created_by = dict["email"] as? String
let question = Question(questionName: questionTitle!, created_by: created_by!)
self.questions.append(question)

print(self.questions.count)
}
}

当我运行它时,它会给我一个错误,说:

线程 1:致命错误:解开包装时意外发现 nil 可选值

我也在 Xcode 9.0 中用 swift 4.0 编写这段代码

。谁能帮忙,我已经为此敲了几个星期了

所以帮助将不胜感激

只需将下面的代码替换为您的代码即可。

let questionTitle = dict["name"] as? String ?? ""
let created_by = dict["email"] as? String ?? ""

它会为你工作。

如果您需要这 2 个值继续执行,我建议您使用guard然后您可以将它们保持在一行中并避免缩进以方便阅读。

defer { print(self.questions.count) }
guard let dict = snapshot.value as? NSDictionary else { return }
guard let questionTitle = dict["name"] as? String else { return }
guard let created_by = dict["email"] as? String else { return }
let question = Question(questionName: questionTitle, created_by: created_by)
self.questions.append(question)

最新更新