John John - 5 months ago 7
iOS Question

How to safely run "myFilter.outputImage!, fromRect: myFilter.outputImage!.extent"?

Sometimes, when I run my app, this line of code

let outputCGImage = context.createCGImage(myFilter.outputImage!, fromRect: myFilter.outputImage!.extent)


crashes the app, I do not know why =/

So, I want to safely run this line. I've tried
myFilter.outputImage?
, but it requires only
!
. So, how can I safely run those line?

I've wanted to try with the guard, but I do not want to pass those line. In this case my filter will not apply,in case of
return
, and I do not want that. I want to apply all my filters successfully.

Any improvements?

Answer

So, I want to safely run this line. I've tried:

context.createCGImage(myFilter.outputImage?,

The first argument to createCGImage() is not an optional type, so you can't use the ?. You can use an if-let:

if let validImage = myFilter.outputImage {
    let outputCGImage = context.createCGImage(validImage, fromRect: validImage.extent)
}
else {
    //Do something else
}