-1

fatal error: unexpectedly found nil while unwrapping an Optional value

With following Code:

weak var previewBlurView : UIVisualEffectView?

func blurPreviewWindow() {
    if (self.previewBlurView == nil) {
        var blurEffect: UIVisualEffect
        blurEffect = UIBlurEffect.init(style: UIBlurEffectStyle.Dark)
        self.previewBlurView? = UIVisualEffectView(effect: blurEffect)
        self.previewView.addSubview(self.previewBlurView?)
        self.previewBlurView!.frame = self.previewView.bounds
    }

    self.previewBlurView?.alpha = 0.0
    UIView.animateWithDuration(0.2, delay: 0.0, options: [.BeginFromCurrentState, .CurveEaseOut], animations: {() -> Void in
        self.previewBlurView?.alpha = 1.0
    }, completion: { _ in })
}

I get the crash on the line:

self.previewView.addSubview(self.previewBlurView?)

NOTE

It turned out that all the views were nil due to an external problem of the view controller's instance not referring to the proper one. So in this case, self.previewBlurView turned out to be nil.

Gizmodo
  • 3,151
  • 7
  • 45
  • 92

1 Answers1

4

Remove the ? in the assignment of self.previewBlurView:

self.previewBlurView = UIVisualEffectView(effect: blurEffect)

What happens otherwise is that the assignment only happens when self.previewBlurView is actually non-nil in the beginning which it is not because you are in the process of assigning something to it.

Compare the following:

var a : Int? = 12
a? = 13
print(a)

var b : Int?
b? = 13
print(b)

Which prints

Optional(13)
nil

The assignment b? = 13 only happens if b is not nil which it unfortunately is.

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • I am still getting the same error, even without it. If I don't do self.view.addSubview(self.previewBlurView!) , I get an error. – Gizmodo Feb 12 '16 at 18:42
  • self.view.addSubview(self.previewBlurView!) That line gives the error. Saying "unexpectedly found nil while unwrapping an Optional value". Even when I remove ? at the assignment, the same. – Gizmodo Feb 12 '16 at 18:45
  • 1
    @gizmodo then please set a breakpoint on that line and inspect what the values are. – luk2302 Feb 12 '16 at 18:47
  • Somehow previewBlurView is nil when I check the values. weak var previewBlurView : UIVisualEffectView? Should that be changed? – Gizmodo Feb 12 '16 at 19:00
  • 1
    @gizmodo ah yes, I overlooked that, remove the 'weak' – luk2302 Feb 12 '16 at 19:02
  • When weak is removed, it's no longer nil ; However, same error on the same line... – Gizmodo Feb 12 '16 at 19:05