1
votes

I'm getting an error when trying to execute a segue from a button to a UINavigatinController:

fatal error: unexpectedly found nil while unwrapping an Optional value

@IBAction func displayFootball(_ sender: Any) {
        self.configToSend = self.configFootball
        performSegue(withIdentifier: "navSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "navSegue" {
        let navVC = segue.destination as! UINavigationController
        let mainVC = navVC.topViewController as! MainViewController //<--This is where the error occurs

        mainVC.config = self.configToSend
    }
}

enter image description here

The first segue is called 'navSegue' and the second is unnamed. Both go directly from one view controller to the next (not from the buttons themselves).

enter image description here

The navVC is NOT nil, btw.

Anyone know why this is happening? Thank you.

1
in your prepare statement, check segue name before taking any action to ensure it is the good segue. if segue.identification == "navSegue" { //actions } also if let navVC = segue.destination as? UINavigationController { //actions } most probably your navVC is nill - GIJOW
Are you sure Gameday Pocket Guide is subclassed as MainViewController? - Martin Muldoon

1 Answers

3
votes

To achieve this, try to use:

let navVC = segue.destination as? UINavigationController
(navVC.viewControllers[0] as? YourVCClass).property = dataToSend

Edit:

The problem of nil on viewControllers array could be because you haven't a relationship segue from NavigationController to his first ViewController

The icon of the segue should be like this one: