0

I'd like to pass my array from my first to my second ViewController. In the end of my first VC I tried to pass it like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let secondVC = ViewController2()
    secondVC.passengers2 = passengers
    print(secondVC.passengers2)

    print(passengers)
    }

"passengers" is my first array in "ViewController.swift" and "passengers2" my sewcond array in "ViewController2.swift".

When I go over to my second VC, the console tells me, that "passengers" and "passengers2" have the same value, but as soon as I am in "ViewController2.swift", "passengers2" is emtpy for some reason.

Does anyone know why?

1
  • 2
    " let secondVC = ViewController2()" That's because you are creating a whole new object and not using the one that is at the end of the segue. let secondVC = segue.destination as ViewController2 instead. Commented Nov 17, 2017 at 10:24

1 Answer 1

3

The problem in your code is that you instantiate a new ViewController2 object, which is never used.

You want to use the destination view controller that is inside your segue object, like that :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destinationViewController as? ViewController2 {
        destinationVC.passengers2 = passengers
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.