无法在当前上下文中推断闭包类型 [英] Unable to infer closure type in the current context
问题描述
在下面函数的第三行,出现以下错误:
On the 3rd line in the function below I get the following error:
无法在当前上下文中推断闭包类型
Unable to infer closure type in the current context
我该如何解决?
func fetchAllUsersImages() {
print("inside func")
self.ref.child("Posts").child(self.userID).child(self.postNum).observe(.childAdded, with: { snapshot in //error here
var images: [URL] = []
if let snapShotValue = snapshot.value as? [String: String] {
for (_, value) in snapShotValue {
if let imageURL = URL(string: value) {
print(imageURL, "image url here")
let imageAsData = try Data(contentsOf: imageURL)
let image = UIImage(data: imageAsData)
let ImageObject = Image()
ImageObject.image = image
self.arrayOfImgObj.append(ImageObject)
self.tableView.reloadData()
}
}
}
})
}
推荐答案
之所以不推断闭包类型,是因为未处理try
语句.这意味着闭包应该会出现"catch"
错误,但是在您的情况下,您忘记了do-try-catch
规则.
The reason why it is not inferring the closure type is because the try
statement is not handled. This means that the closure expected to "catch"
the error, but in your case, you forgot the do-try-catch
rule.
因此,您可以尝试使用以下答案来捕获错误:
Therefore you can try the following answer which will catch your errors:
do {
let imageAsData = try Data(contentsOf: imageURL)
let image = UIImage(data: imageAsData)
let ImageObject = Image()
ImageObject.image = image
self.arrayOfImgObj.append(ImageObject)
} catch {
print("imageURL was not able to be converted into data") // Assert or add an alert
}
然后您可以断言错误(以进行测试),或者我个人会设置警报.
You can then assert an error (for testing), or what I would personally do, is set up an alert.
这样,应用程序不会崩溃,而是通知用户.我发现这非常很有用,在旅途中且未插入设备的情况下-因此我可以看到错误消息,而不是无所事事的崩溃,不知道发生了什么事.
This way the app wouldn't crash, but instead, notify the user. I find this very helpful when on the go and my device isn't plugged in - so I can see the error messages instead of a blank crash with no idea what happened.
这篇关于无法在当前上下文中推断闭包类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!