简体   繁体   中英

How to data in segue using Swift

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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM