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.
Remove the
?in the assignment ofself.previewBlurView:What happens otherwise is that the assignment only happens when
self.previewBlurViewis actually non-nilin the beginning which it is not because you are in the process of assigning something to it.Compare the following:
Which prints
The assignment
b? = 13only happens ifbis notnilwhich it unfortunately is.