0

I created a label to show the current date when the view loads, but when I transition to another view, I get the: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.

The UILAbel works fine and shows the current date, but when I press the button to go to the other View, then it crashes giving the error message at the:

theDate.text = formatter.string(from: date)

The button also works fine if I remove the code in the viewDidLoad

I did check the connections they are linked.

I am very new to swift, been stuck for a while now trying to solve this.

class ViewController: UIViewController {

    @IBOutlet weak var theDate: UILabel!
    @IBAction func but_test(_ sender: Any) {
        
      let testing = storyboard!.instantiateViewController(withIdentifier: "blue_vc")
      present(testing, animated: true, completion: nil)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let date = Date()
        let formatter = DateFormatter()
        formatter.timeZone = .current
        formatter.dateStyle = .medium
        formatter.locale = .current
        theDate.text = formatter.string(from: date) //I get the error message here. 
        
    }

}
Pedro
  • 1
  • 1
  • Your variable `theDate` is an IBOutlet. It is set up as an "implicitly unwrapped optional" so if it is nil, your code will crash (as you report.) Set a breakpoint on that line and examine `theDate`. It is almost certainly nil. Then go to your storyboard and re-check that the outlet is connected. I bet it's not. It is not clear what you mean about the button. Is your "blue_vc" also set up in your storyboard as an instance of "ViewController"? It probably shouldn't be unless it has all the same outlets and buttons. – Duncan C Aug 23 '22 at 15:40
  • I added a print function to show the value of `theDate` before and after the line with the fatal error, and placed a breakpoint at the line. When I run it, before the line, it prints the default value of the IBOutlet as in the Storyboard, after the breakpoint, it changes to the actual date. By "the button", I meant the IBAction 'but_test', when I trigger that button to instantiate, it does prints out nil. – Pedro Aug 25 '22 at 15:12
  • But why do you visit viewDidLoad in your ViewController class after instantiating your `blue_vc`? Are both the view controller with the button and the VC in the storyboard with the ID of `blue_vc` instances of your `ViewController` class? – Duncan C Aug 25 '22 at 16:54
  • (Open your storyboard. Find the view controller with the identifier of "blue_vc" and select it's "scene" in the storyboard. Then go to the view menu>Inspectors and select "identity" to display the identity inspector. Add that info to your question and post a comment here. If the view controller with the ID "blue_vc" is of class "ViewController", that is your problem. – Duncan C Aug 25 '22 at 17:06

0 Answers0