ios - 抛出函数的无效转换。使用解码器类时
问题描述
我正在使用解码器类来解析 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
}
我收到此错误:
解决方案
我只是要解释“无效转换”错误,因为这就是你所问的。术语有点混乱,但基本问题非常清楚。
你会承认,我想,你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
不抛出。所以该选项被删除。因此还剩下什么?您必须执行以下操作之一:
将您的呼叫包裹
toObject
在do
do/catch
使用
try?
代替try
使用
try!
代替try
我推荐第一个。
推荐阅读
- javascript - Issues with using negative numbers in a prompt box
- c# - How to add a new page to a website in visual studio
- c - How to copy the semester[20] string under the structure, and count and print it in my output
- clam - Can't stop Clamav deamon in Linux
- c# - Stop Validation on Empty DateTime field returning Invalid in ModelState Core 3
- azure - what will be the request body for create repository in azure devops?
- python - Python 字典 - 值子列表
- python - OKTA Sso 蟒蛇
- kubernetes - 有没有办法批量重启部署以在 kubernetes v1.15.2 中应用配置更改
- r - 将数据框中的某些列替换为另一个数据框的列