【问题标题】:Unwrapping a optional nil when getting value out of a firebase snapshot dictionary in swift 4.0在 swift 4.0 中从 firebase 快照字典中获取值时打开一个可选的 nil
【发布时间】:2018-09-17 06:59:02
【问题描述】:

在 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 中编写此代码

谁能帮我解决这个问题好几个星期了

非常感谢您的帮助

【问题讨论】:

  • 检查您的字典的 keys 是否返回有效的String values。
  • 让 question = Question(questionName: questionTitle!, created_by: created_by!) 在这一行你可以删除!签名。
  • @SagarBhut 我试过了,但它给了我一个错误并自动完成它有一个问号
  • 您需要将 let questionTitle = dict["name"] 的默认值设置为? String let created_by = dict["email"] as?将字符串替换为 let questionTitle = dict["name"] as?细绳 ?? "" 让 created_by = dict["email"] as?细绳 ?? ""

标签: ios firebase firebase-realtime-database swift4


【解决方案1】:

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

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

它会为你工作。

【讨论】:

    【解决方案2】:

    如果您需要这 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      相关资源
      最近更新 更多