Home > Mobile >  Passing a Model between View Controllers
Passing a Model between View Controllers

Time:08-19

I am struggling to pass a model of data from one controller to the next. I am sure I am just missing something very simple but hoping I can get some help.

Below I create the code to select all the data from the row that was selected:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        print(indexPath.row)
        
        let passingData = arrivals[indexPath.row]
        print(passingData)
        let controller = storyboard?.instantiateViewController(withIdentifier: "FlightInfoVC") as! FlightInfoViewController
        controller.flightDataPassedIn = passingData
        //Code incomplete - Will add execution to show VC
        
    }

That print statement is reflected below: console

Now where I am struggling is to get that data to go to my next view controller. Setting the array of data in my new VC doesn't seem to work because it is expecting a type of 'FlightModel' but I cannot seem to figure out how to declare that. I have tried this but I cannot convert type [Any] to 'FlightModel'

var flightDataPassedIn: FlightModel = []

Appreciate any help you can give!

CodePudding user response:

It sounds like the issue is that you're trying to initialize flightDataPassedIn with a value of [], which is of incompatible type [Any].

If you're okay with the flightDataPassedIn property on FlightInfoViewController being optional, that might be the most straightforward solution. It would automatically be initialized to nil, so would not require you to set an initial value - just declare it like this:

var flightDataPassedIn: FlightModel?

If you don't want it to be optional, initialize it to a default value of type FlightModel (add an initializer to FlightModel if necessary) and overwrite it with passingData from the parent ViewController.

Hope this helps!

CodePudding user response:

The issue was that I was not passing the data via the main required function that everyone uses Prepare for segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "TrackingToInfo" {
            if let destinationVC = segue.destination as? FlightInfoViewController {
                destinationVC.flightDataPassedIn = readyToPass
            }
        }
    }

Within the tableview I had to set the data to a var in my currentVC of type FlightModel? then the data passed

  • Related