Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
I am using this line of code

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?
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
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.
 
  • Like
Reactions: SylvainLafrance

KALLT

macrumors 603
Sep 23, 2008
5,361
3,378
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.