hightech hightech - 1 year ago 98
Swift Question

Swift - SecondViewController to FirstViewController: fatal error: unexpectedly found nil

I am trying to figure out how to fix this issue in Swift and I am also having this error: "fatal error: unexpectedly found nil while unwrapping an Optional value". Any suggestion appreciated. Thanks.

From FirstViewController

func getDatafromSecondViewController(myMessage: String){



From SecondViewController

func sendThisDataToFirstViewController() {

let firstViewController = FirstViewController()

Note: I cannot use prepareForSegue because I am using those files "class FirstViewController: UIViewController" and "class SecondViewController: NSObject" as an example.

Answer Source

If I'm not wrong, I think that by using those you are able to print myMessage to the console but when you try with a variable, it doesn't work. If that is the case I think the issue is the following:

When you do let firstViewController = FirstViewController() you are creating a new view controller of type FirstViewController and named firstViewController. It is just created so any variables that where not assigned in it would be nil, thus would throw this error. You need a reference to the original FirstViewController. You need a delegate to do that.

An easy way to achieve what you want to do is the following. Assign your first view controller in the second right before you segue to it:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
            if segue.identifier == "yourSegueIdentifierHere" {
                let nextViewController = segue.destinationViewController as SecondViewController
                nextViewController.myVariable = self.variableToPass

Of course you need that variable to exist in the view controller that will appear so declare it near the top but inside the class:

var myVariable: YourTypeHere!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download