在控制器之间传递变量 - Swift4

Pass a variable between controllers - Swift4

我正在尝试将 1 个变量传递给另一个视图控制器,然后再传递给另一个视图控制器。

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

当我 select 在一个单元格上时,我可以访问一个变量 selectedPlace

我想将它传递给我的 PlaceDetailVC 和 MapVC。

出于某些原因,我无法做到这一点。

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

我也试试

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,"<<<<<<")


结果

我一直在

关于我做错了什么的任何提示?

如果 segue "toMap" 由导航按钮

调用,则无需检查 indexPath
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
    }*/

  }
}