Unable to infer closure type in the current context

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.


This error can also happen if you have a non related compilation error in your closure body. For example, you may be trying to compare two or more non-boolean types.

extension Array where Element == Resistance {
    init(_ points: [Point]) {
        let peaks = points.beforeAndAfter { (before, current, after) -> Bool in
            before < current && current > after
        }
        self = []
    }
}

will produce Unable to infer closure type in the current context.
The correct code:

extension Array where Element == Resistance {
    init(_ points: [Point]) {
        let peaks = points.beforeAndAfter { (before, current, after) -> Bool in
            before.value < current.value && current.value > after.value
        }
        self = []
    }
}