【问题标题】:Could not cast value of type '__NSDictionaryM' (0x1111152b0) to 'FIRDataSnapshot' Firebase Swift 3无法将“__NSDictionaryM”(0x1111152b0)类型的值转换为“FIRDataSnapshot”Firebase Swift 3
【发布时间】:2018-02-27 16:55:39
【问题描述】:

我正在尝试从 Firebase 数据库中读取嵌套数据结构,但我不知道如何处理 [String:AnyObject] 类型的对象可能为 nil 的情况。
readFeesCleaner(callback_) 被调用时,它会抛出一个错误。

  func readFeesCleaner(callback: @escaping ((_ feesCleaner: FeesCleaner) -> Void)) {

 dbRef.child("FeesCleaner").child(self.uidOfTextField!).observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in

        guard !(snapshot.value is NSNull) else {
            return
        }

       //throws error: signal SIGABRTCould not cast value of type '__NSDictionaryM' (0x1111152b0) to 'FIRDataSnapshot' (0x10ef16d18).
            let feesCleanersReceived = FeesCleaner(snapshot: (snapshot.value)! as! FIRDataSnapshot)
                callback(feesCleanersReceived)

    }) { (error:Error) in
        print(#line, "\(error.localizedDescription)")
    }
 } 


struct FeesCleaner {

   var outstandingFees: AnyObject!
   var timeStampFeesSaved: [String:AnyObject]!
   var backgroundCheck: AnyObject!

    init(
       outstandingFees: AnyObject? = nil, //value might not exist when reading
       timeStampFeesSaved: [String:AnyObject]? = nil,// value might not exist when reading
       backgroundCheck: AnyObject) {

       self.outstandingFees = outstandingFees
       self.timeStampFeesSaved = timeStampFeesSaved
       self.backgroundCheck = backgroundCheck   
  }//end of init

    //read data here
     [full struct data here][1]
      https://gist.github.com/bibscy/dc48f7107459379e045a50fdbbc35335


}//end of struct

【问题讨论】:

    标签: firebase swift3 firebase-realtime-database


    【解决方案1】:

    这里有很多问题。第一:

    当对象类型为 [String:AnyObject] 时如何管理这种情况 可能为零。

    你已经用前面的语句处理了,注意你也可以添加

    if snapshot.exists == false {return}
    

    第二:您必须正确处理可选参数 - 如果 var 可以为 nil,您需要适当的代码来处理这种情况,而不是通过它。如果你强制解开一个可选项,你实际上是在肯定它永远不会为零,所以基本上,不要那样做。

    一种解决方法是简单地将快照作为 DataSnapshot 传递,然后一次提取一个属性;如果它们存在,则分配它们,如果未设置为 0 或 nil 或其他占位符。

    Firebase 闭包中的类似内容:

    let feesCleanersReceived = FeesCleaner(withSnapshot: snapshot)
    

    然后你的结构是这样的:注意我们正在利用 nil 合并运算符,??

    struct FeesCleanerStruct {
        var outstandingFees: String?
        var timeStampFeesSaved: String?
    
        init(withSnapshot: DataSnapshot) {
            let dict = withSnapshot.value as! [String: Any]
            self.outstandingFees = dict["outstandingFees"] as? String ?? "0.0"
            self.timeStampFeesSaved = dict["timeStampFeesSaved"] as? String ?? "0"
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多