nil found while unwrapping optional value

Discussion in 'iOS Programming' started by theprizerevealed, May 6, 2019.

  1. theprizerevealed macrumors regular

    Feb 26, 2016
    I am using this line of code

     self.view.window!.rootViewController?.dismiss(animated: false, completion: nil) 
    in my app and sometimes, though not always, Xcode will tell me the error message 'nil found while unwrapping optional value', while using the Simulator. I can't seem to replicate the behavior that triggers this error message. Any ideas?
  2. theprizerevealed thread starter macrumors regular

    Feb 26, 2016
  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Force unwrapping is usually a bad idea unless you're certain that the optional can't be nil. You can easily fix this by changing the ! to a ?. I can't say why the window might be nil but that looks like the only part of that expression that can cause that error.
  4. KALLT macrumors 601

    Sep 23, 2008
    Adding a ? here would prevent the app from crashing, but it also stops this method from being called, without giving you immediate feedback.

    It is generally useful to check the documentation in which case a property may be nil. For instance, the window property of UIView is nil if the view has not yet been added to a window.

Share This Page

3 May 6, 2019