我正在尝试从Firebase数据库中读取嵌套数据结构,但是当[String:AnyObject]类型的对象可能为零时,我不知道如何管理这种情况。
调用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
答案 0 :(得分:1)
这里有很多问题。第一:
如何处理[String:AnyObject]类型的对象时的情况 可能是零。
您已使用之前的声明处理过该声明,并指出您也可以添加
if snapshot.exists == false {return}
第二:您必须正确处理选项 - 如果var可能为零,您需要使用代码来处理这种情况而不是通过它。如果你强行打开一个可选项,你基本上就是说它肯定不会是零,所以基本上不会这样做。
一个修复可能是简单地将快照作为DataSnapshot传递,然后一次拉出一个属性;如果它们存在,则分配它们,如果没有设置为0或零或其他占位符。
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"
}
}