Adrienne
Adrienne

Reputation: 2680

Why is this variable "nil" even though I have an "if" statement that checks it not to be

Even though I check whether self.photoImageView.image != nil, I am still getting a fatal error: unexpectedly found nil while unwrapping an Optional value error when I try to applyBlurEffect in the penultimate line.

Do you know how to reconcile this?

if (output?.getAccel() == true){
        if (output?.getImage() != nil){
            if (self.photoImageView.image != nil){
                println(photoImageView.image)
                var blurredImage = self.applyBlurEffect(self.photoImageView.image!)
                self.photoImageView.image = blurredImage
            }

For context, I have a photoImageView, and when an "accelerometer button" is plugged into that photoImageView, this function takes that image, blurs it, and updates the image as a blurred image.

Also when I print photoImageView.image, it returns Optional(<UIImage: 0x174087d50> size {1340, 1020} orientation 0 scale 1.000000). Therein may lie the problem but I need a little help to solve it.

Upvotes: 0

Views: 88

Answers (1)

Vasil Garov
Vasil Garov

Reputation: 4921

In Swift you have to use optional binding to make sure that an optional is not nil. In this case you should do something like this:

if let image = self.photoImageView.image {
    //image is set properly, you can go ahead
} else {
    //your image is nil
}

It is a very important concept in Swift so you can read more here.

UPDATE: As @rdelmar stated, optional binding is not obligatory here, checking for nil should also be enough. Personally I prefer using optional binding though. One of its benefits is the multiple optional binding instead of checking all optionals for nil:

if let constantName = someOptional, anotherConstantName = someOtherOptional {
    statements
}

Upvotes: 2

Related Questions