Search code examples
iosswifttableviewsegueuistoryboardsegue

Pass a variable between controllers - Swift4


I'm trying to pass 1 variable to another view controller and then another view controller.

var selectedPlace = Place {
    name = Daniel Webster Highway;
    country = United States;
    lat = 42.72073329999999;
    lon = -71.44301460000001;
} 

enter image description here

When I select on a cell, I have access to a variable selectedPlace

I want to pass it on to my PlaceDetailVC and also MapVC.

For some reasons, I can't make that happen.

PlacesVC

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

    let destinationVC = segue.destination as! PlaceDetailVC
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.selectedPlace = (places?[indexPath.row])!
        destinationVC.selectedTrip = selectedTrip!
    }

}

PlaceDetailVC

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

    if segue.identifier == "toMap" {
        let destinationVC = segue.destination as! MapVC
        if let indexPath = placesTable.indexPathForSelectedRow {
            destinationVC.selectedPlace = selectedPlace
        }
    }
}

I also try

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! MapVC
    if let indexPath = placesTable.indexPathForSelectedRow {
        destinationVC.selectedPlace = selectedPlace
    }
}

MapVC

print(selectedPlace,"<<<<<<")


Result

I kept getting

enter image description here

Any hints on what I did wrong ?


Solution

  • No need to check indexPath if the segue "toMap" is called by the nav button

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
    if segue.identifier == "toMap" {
        let destinationVC = segue.destination as! MapVC
        destinationVC.selectedPlace = selectedPlace
    
        /*
        if let indexPath = placesTable.indexPathForSelectedRow {
            destinationVC.selectedPlace = selectedPlace
        }*/
    
      }
    }