title: Passing data from UITableViewDataSource to UIViewController using protocol and delegate in Swift
body: <p>I'm trying to pass data from a UITableViewDataSource to a UIViewController when a table row is selected. I think I'm pretty close. </p>
  
  <p><strong>Protocol</strong></p>
  
  <pre><code>protocol BusDataDelegate {
      func didSelectRow(row: NSIndexPath, data: Route)
  }
  </code></pre>
  
  <p><strong>Data Source</strong></p>
  
  <pre><code>class BusUITableView: NSObject, UITableViewDelegate, UITableViewDataSource {
  
      var busDataDelegate: BusDataDelegate?
  
      var routeService: RouteService = RouteService()
  
      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
  
          var busRoutes: [Route] = routeService.retrieve()
          return busRoutes.count
      }
  
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
  
          var cell:BusUITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as BusUITableViewCell
  
          var busRoutes: [Route] = routeService.retrieve()
  
          cell.routeName.text = busRoutes[indexPath.row].name
          cell.routeNumber.text = busRoutes[indexPath.row].id
          return cell
      }
  
      func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  
          var busRoutes: [Route] = routeService.retrieve()
  
          busDataDelegate?.didSelectRow(indexPath, data: busRoutes[indexPath.row])
          println("You selected cell #\(indexPath.row)!")
  
      }
  
  }
  </code></pre>
  
  <p><strong>View Controller</strong> - abbreviated</p>
  
  <pre><code>class ViewController: UIViewController, MKMapViewDelegate, BusDataDelegate {
  
      func didSelectRow(row: NSIndexPath, data: Route) {
          println("Row: \(row) Data: \(data)")
      }
  
  }
  </code></pre>