Unexpectedly found nil IBOutlet in prepareForSegue

I have a detail view controller, and I would like to set the label text to a value taken from an array using an indexPath row.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "showView"){
        let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
        let indexPath = self.MainTableView.indexPathForSelectedRow!
        detailVC.label.text = "Test"
        self.MainTableView.deselectRowAtIndexPath(indexPath, animated: true)
        }
}

I keep getting a fatal error: unexpectedly found nil while unwrapping an optional value. I have tried switching detailVC.label.text = "Test" to detailVC.label.text = names[indexPath.row] but I keep getting the same error every time.

I used the same lines of code for changing the cell's label text, with no errors, but for this label in the center of a blank view I cannot seem to get it right? Any thoughts on what needs to be changed?

By the way, the label in the detail view controller is @IBOutlet weak var label: UILabel!


Solution 1:

You cannot access IBOutlets of DetailViewController in prepareForSegue because they are not connected yet.

As mentioned in the comments create a String property in DetailViewController, set it in prepareForSegue and set the text property of the label in viewDidLoad or viewWillAppear of DetailViewController.

Solution 2:

The alternative is to call detailVC.loadViewIfNeeded() before setting the property. It will load all your IBOutlet's