Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Please help! I am trying to make an app, with the user setting their name so it can be later displayed on a label such as: Welcome, (username). But when trying to run my code, xcode gives me an error: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value. Here is my code:




class HomeViewController: UIViewController {

    @IBOutlet weak var displayLbl: UILabel!

    @IBOutlet weak var textField: UITextField!

    @IBOutlet weak var submitBtn: UIButton!

    

    var result : String!

    

    override func viewDidLoad() {

        super.viewDidLoad()



        

        displayLbl.text = ""

        

        submitBtn.setTitle("Submit", for: UIControl.State.normal)

        

    }

    

    @IBAction func submitAction(_ sender: Any) {

        

        result = textField.text!

        displayLbl.text = "\(result!)"

        

    }

    

It gives me an error on (displayLbl.text = ""), but I don't know what to do about it. Please help

You are getting an error because displayLbl is an implicitly unwrapped optional whose value is nil. You declared the type to be UILabel!. By adding the ! character you set your app to crash if the outlet is nil and your code accesses the outlet.

The most likely cause of the error is that the display label outlet is not connected to the label in the storyboard. Connecting the label in the storyboard to the outlet should fix that error.

Your submitAction function also has the potential for the same error because you are force unwrapping optionals. When you add ! to a variable name, and that variable is nil, your app is going to crash.

The following article has more details on dealing with the error you're getting:

https://www.swiftdevjournal.com/fixing-the-thread-1-fatal-error-unexpectedly-found-nil-while-implicitly-unwrapping-an-optional-value-error/

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
 
 
Q