Ios 从抛出函数的转换无效。什么时候使用解码器类

Ios 从抛出函数的转换无效。什么时候使用解码器类,ios,swift,iphone,exception,compiler-errors,Ios,Swift,Iphone,Exception,Compiler Errors,我使用decoder类解析firebase firestore的json响应 这是我用于解析的扩展: extension DocumentSnapshot { func toObject<T: Decodable>() throws -> T { let jsonData = try JSONSerialization.data(withJSONObject: data()!, options: []) let obje

我使用decoder类解析firebase firestore的json响应

这是我用于解析的扩展:

extension DocumentSnapshot {
    func toObject<T: Decodable>() throws -> T {
        
        let jsonData = try JSONSerialization.data(withJSONObject: data()!, options: [])
        let object = try JSONDecoder().decode(T.self, from: jsonData)
        
        return object
    }
}
这是我使用DocumentSnapshot扩展方法“toObject”的函数

    plasmaRequestIDs.forEach { (document) in
        
        Firestore.firestore().collection("plasma_request").document(document).addSnapshotListener { (documentSnapshot, error) in
            
            
            guard let err = error else{return}
            
            guard let snapshot = documentSnapshot else {return}
            
            if snapshot.exists{
                
                
                let requestobj:PlasmaRequest =  try snapshot.toObject()
                plasmaRequestList.append(requestobj)
                
                if index == plasmaRequestIDs.count - 1 {
                    
                    successHandler(plasmaRequestList)
                    
                }
                
            }
            
        }
        
        index = index + 1
    }
我得到这个错误:

Invalid conversion from throwing function of type '(DocumentSnapshot?, Error?) throws -> Void' to non-throwing function type '(DocumentSnapshot?, Error?) -> Void'

我只想解释一下“无效转换”错误,因为这就是您要问的所有问题。术语有点混乱,但根本问题是非常清楚的

我想,你会承认你的
toObject
是一个抛出函数吗?注意单词
抛出

func toObject<T: Decodable>() throws -> T {
好吧,但是斯威夫特对你在哪里可以这么说非常严格;您只能在两个地方说
try

  • do/catch
    结构的
    do

  • 函数中抛出

但你两个都不在!你在这里:

Firestore.firestore().collection("plasma_request")
    .document(document)
        .addSnapshotListener { 
            (documentSnapshot, error) in
.addSnapshotListener
的闭包不会抛出。因此,该选项被删除。那么剩下什么呢?您必须执行以下操作之一:

  • 将对
    do/catch

  • 使用
    try?
    而不是
    try

  • 使用
    试试而不是
    尝试


我推荐第一个。

您看过
FirebaseFirestoreSwift
的内置自定义对象支持吗?
Firestore.firestore().collection("plasma_request")
    .document(document)
        .addSnapshotListener { 
            (documentSnapshot, error) in