title: Swift passing data between views
body: <p>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.</p>
  
  <p>I have a UITableView and I am able to read the contents of the selected cell without issue:</p>
  
  <pre><code>override func tableView(_ tableView: UITableView, didSelectRowAt 
  indexPath: IndexPath) {
      let cell = self.tableView.cellForRow(at: indexPath)
      selectedItem = (cell?.textLabel?.text)!
  }
  </code></pre>
  
  <p>I have a variable set at the top of my class like so:</p>
  
  <pre><code>var selectedItem: String = String()
  </code></pre>
  
  <p>I then use a prepare for seque to seque to the new page/view and pass in the data selected:</p>
  
  <pre><code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "showDetails"
      {
          if let destinationVC = segue.destination as? ItemDetails {
              destinationVC.detailsToDisplay = selectedItem
          }
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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).</p>
  
  <p>Thanks!</p>