Swift optional variable is a variable that can have nil ( same to null ) value. And you do not need to initialize an optional variable before using it. If not initialized, the optional variable value is nil. It does not like none optional variable which you must assign an initial value before using it.
1. How To Declare A Swift Optional Variable.
- To declare an optional variable, you need to add a question mark (
?) at the end of variable declaration like below.
- If you do not initialize an optional variable with a value, then its value is nil. If you want to use its value later, you should add an exclamation mark (
!) after the variable name to unwrap it.
- You can read the article How To Fix Error ‘Value Of Optional Type Must Be Unwrapped To A Value Of Type’ In Swift to learn more about swift optional variable usage.
2. How To Fix Fatal Error: Unexpectedly Found Nil While Unwrapping An Optional Value.
- In my example project, I meet an error message like this, Fatal error: Unexpectedly found nil while unwrapping an Optional value. Just as the error message said, one variable value is nil in my swift source code, and I use that nil variable in my swift source code later.
- So to resolve this kind of error, you had better set a breakpoint at the code line that triggers the error like the below picture, and then debug your source code to see why the variable value is nil. You can read the article How To Debug And Get Error Messages In Xcode Step By Step to learn more.
3. The Reason For Fatal Error: Unexpectedly Found Nil While Unwrapping An Optional Value.
- After debug and investigate, I finally find the reason that triggers the fatal error in my project.
- The reason for variable imageIcon‘s value is nil is because the variable loaded image has been removed from the hard disk. Below are the steps that cause the error.
- First, I add two image files under the Xcode project.
- But later I move the two images from the project to the under-level project folder. But the two images still exist under the Xcode project, so I want to delete them. I select and right-click the two images and then click Delete menu item in the popup menu list to remove them.
- Then it will popup below confirm dialog, there are two buttons that I can choose, one is Remove References the other is Move to Trash. The Remove References button will only remove the image file references from the Xcode project, and the image file still exists. The Move to Trash button will remove the two image files permanently from the hard disk. I click the Move to Trash button, and this cause the error occurred, the imageIcon variable load a not exist image, so imageIcon variable’s value is nil. The correct action is to click the Remove References button to remove the image reference from the Xcode project but not remove image files from the hard disk.