title: IOS/Swift rendering table after JSON request
body: <p>I am new to IOS and swift. I am trying to implement an api get request that returns json and then display it in a table. Below is my current code. When I run simulator I am getting the following error:</p>
  
  <p>fatal error: Cannot index empty buffer</p>
  
  <p>If I remove the hardcoded return 3 in the tableView function and instead use doDatItems.count nothing renders in the table because I guess the array of doDatItems starts empty before the get request is made. It seems like a timing thing? How do I ensure the get request is made before the table loads?</p>
  
  <pre><code>import UIKit
  
  class ViewController: UIViewController, UITableViewDelegate {
  
      var doDatItems:[String] = []
  
      @IBOutlet weak var doDatItem: UITextField!
  
      @IBOutlet weak var yourDoDats: UILabel!
  
      @IBAction func addDoDat(sender: AnyObject) {
  
          doDatItems.append(doDatItem.text)
  
          println(doDatItems)
      }
  
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          let urlPath = "http://localhost:3000/dodats"
          let url: NSURL = NSURL(string: urlPath)!
          let session = NSURLSession.sharedSession()
  
          let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -&gt; Void in
              println("Task completed")
              if((error) != nil) {
                  // If there is an error in the web request, print it to the console
                  println(error.localizedDescription)
              }
              var err: NSError?
              var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &amp;err) as NSDictionary
              if(err != nil) {
                  // If there is an error parsing JSON, print it to the console
                  println("JSON Error \(err!.localizedDescription)")
              } else {
                  let dataArray = jsonResult["dodats"] as [String]
  
                  for item in dataArray {
                    self.doDatItems.append(item)
                  }
  
  //                println(self.doDatItems)
  
              }
  
          })
  
          task.resume()
      }
  
      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
  
          return 3
  
      }
  
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell
      {
  
          let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
  
          println(self.doDatItems)
  
          cell.textLabel?.text = self.doDatItems[indexPath.row]
  
          return cell
      }
  
  
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
  
  
  }
  </code></pre>