首页 > 解决方案 > 抛出函数的无效转换。使用解码器类时

问题描述

我正在使用解码器类来解析 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
    }
}

但是当我从文档 ID 列表中获取文档时。

然后我收到此错误:

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

这是我使用 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
    }

我收到此错误:

在此处输入图像描述

标签: iosswiftiphoneexceptioncompiler-errors

解决方案


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

你会承认,我想,你toObject是一个投掷函数?注意这个词throws

func toObject<T: Decodable>() throws -> T {

因此,当您调用它时,您正确地承认这一事实,通过调用它try

let requestobj:PlasmaRequest =  try snapshot.toObject()

好的,但是 Swift 对你可以说的地方非常严格;你只能try在两个地方说:

  • do一个do/catch结构中

  • 在一个throws函数中

但你不在其中!你在这个:

Firestore.firestore().collection("plasma_request")
    .document(document)
        .addSnapshotListener { 
            (documentSnapshot, error) in

关闭.addSnapshotListener不抛出。所以该选项被删除。因此还剩下什么?您必须执行以下操作之一:

  • 将您的呼叫包裹toObjectdodo/catch

  • 使用try?代替try

  • 使用try!代替try

我推荐第一个。


推荐阅读