iosswiftoption-typeforced-unwrapping

Unwrapping optional crash in Swift


I am new trying to understand debugging and I have a challenge I am working through. I have queried for a solution to this issue and not found it within StackOverflow. I am tying to better understand what is happening here and why this crash occurs.

I have tracked down the bug via print statements in my source code. I added a print statement to the beginning of this function to confirm that the block is being reached.

@IBAction func bugTypeSelected(_ sender: UIButton) {
    print("bugTypeSelected reached")
    bugFactory.currentBugType = BugFactory.BugType(rawValue: Int(sender.currentTitle!)!)!
    self.dismiss(animated: true, completion: nil)
}

When I run the app and click one of the bugs in the settings modal, the print statement is printed to the console and then the app crashes. Xcode is telling me that the issue lies within this line:

bugFactory.currentBugType = BugFactory.BugType(rawValue: Int(sender.currentTitle!)!)!

The error reads

“Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.”

So, I understand that using a nil value will crash the app. I also understand that I am working with optionals here. I am stuck on what to do next.


Solution

  • The problem with that line is you are force to unwarp values if value nil or not a data type which you force to caste means app will crash

    Instead of force to unwarp use optional unwarp like below

    if sender.currentTitle != nil {
      if let requiredIntValue = Int(sender.currentTitle!){
        if let bugType = BugFactory.BugType(rawValue: requiredIntValue)?{
           bugFactory.currentBugType = bugType
        }
      }
    }
    

    Hope this will help you