Unable to infer closure type in the current contex

2020-04-10 18:56发布

On the 3rd line in the function below I get the following error:

Unable to infer closure type in the current context

How do I fix this?

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()
                }
            }
        }
    })
}

1条回答
Viruses.
2楼-- · 2020-04-10 19:20

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.

查看更多
登录 后发表回答