(Swift) PrepareForSegue: fatal error: unexpectedly found nil while unwrapping an Optional value

Velocity picture Velocity · Aug 21, 2014 · Viewed 8.7k times · Source

DetailViewController:

    @IBOutlet var selectedBundesland: UILabel!

TableViewController:

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {


    if (segue.identifier == "BackToCalculator") {
        var vc:FirstViewController = segue.destinationViewController as FirstViewController
            vc.selectedBundesland.text = "Test"
    }

IBOutlet is connected!

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

I read multiple pages about Optionals but i didn't know the answer to my problem.

Do you need more information about my project?

Answer

Paulw11 picture Paulw11 · Aug 21, 2014

You cannot write directly to the UILabel in prepareForSegue because the view controller is not fully initialised yet. You need to create another string property to hold the value and put it into the label in the appropriate function - such as viewWillAppear.