Q:

Swift passing data between views

I am working on a Swift app and I've run into a slightly weird issue.  I'm quite new to Swift and iOS development so think I may not be doing this the correct way.
I have a UITableView and I am able to read the contents of the selected cell without issue:
override func tableView(_ tableView: UITableView, didSelectRowAt 
indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath)
    selectedItem = (cell?.textLabel?.text)!
}

I have a variable set at the top of my class like so:
var selectedItem: String = String()

I then use a prepare for seque to seque to the new page/view and pass in the data selected:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails"
    {
        if let destinationVC = segue.destination as? ItemDetails {
            destinationVC.detailsToDisplay = selectedItem
        }
    }
}

The problem is that while the data does get passed between the views and appears in the UI, it's not the most recent data.  For example when I run the code and select the item, the first time, nothing appears, but if I click the back button, select the item again, this time it does appear in the next view.  And on subsequent selections in the UI, it navigates to the next view but doesn't update the text until I pick another item.
In my mind it's almost like the selectedItem variable is not being set on each selection as I expect and passed through, but instead on subsequent selections in the UI, it is updated.
How do I get this to pass the actual correct item each time and not the previous one or none at all (which is what happens on the first run).
Thanks!

A:

Your prepare for segue called before the didSelectRow at index
change the code like below 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails"
    {
        if let destinationVC = segue.destination as? ItemDetails {

let cell = tableView.cellForRowAtIndexPath(self.tableView.indexPathForSelectedRow!) as UITableViewCell

destinationVC.detailsToDisplay = (cell.textlabel?.text)!

        }
    }
}

