0
votes

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){

         println(myMessage)

    }

From SecondViewController

    func sendThisDataToFirstViewController() {

         let firstViewController = FirstViewController()
         firstViewController.getDatafromSecondViewController("Testing")
    }

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

1
How are these two controllers getting on screen? This line, let firstViewController = FirstViewController() is creating a new instance of FirstViewController that's not the one you have/had on screen.rdelmar
your code works fine for me :)HamzaGhazouani
Can't see any reason why this code would cause this error.Mike Sand
@rdelmar I cannot use prepareForSegue because I am using those files "class FirstViewController: UIViewController" and "class SecondViewController: NSObject".hightech

1 Answers

1
votes

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!