无法将“__NSDictionaryM”类型的值 (0x1111152b0) 转换为 'FIRDataSnapshot' Firebase Swift 3

Could not cast value of type '__NSDictionaryM' (0x1111152b0) to 'FIRDataSnapshot' Firebase Swift 3

我正在尝试从 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

这里有很多问题。第一:

how to manage the case when an object of type [String:AnyObject] could be nil.

您已使用先前的语句处理了该问题,并指出您还可以添加

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"
    }
}