title: Swift: Display image from UIImage array in table view
body: <p>I am getting images from an async request and adding them to a <code>[UIImage]()</code> so that I can populate my <code>UITableView</code> images with those from the array. The problem is, I keep getting <code>Fatal error: Array index out of range</code> in the <code>cellForRowAtIndexPath</code> function when this is called, and I suspect it may be because I'm making an async call? Why can't I add an image from the array to the table view row?</p>
  
  <pre><code>   var recommendedImages = [UIImage]()
  
          var jsonLoaded:Bool = false {
              didSet {
                  if jsonLoaded {
  
                      // Reload tableView on main thread
                      dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
                          dispatch_async(dispatch_get_main_queue()) { // 2
                              self.tableView.reloadData() // 3
                          }
                      }
  
                  }
              }
          }
  
      override func viewDidLoad() {
              super.viewDidLoad()
  
             // ...
  
            let imageURL = NSURL(string: "\(thumbnail)")
  
            let imageURLRequest = NSURLRequest(URL: imageURL!)
  
            NSURLConnection.sendAsynchronousRequest(imageURLRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in
  
            if error != nil {
  
                println("There was an error")
  
           } else {
  
                let image = UIImage(data: data)
  
                self.recommendedImages.append(image!)
  
                self.jsonLoaded = true
  
           }
  
          })
  
      }
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
  
          var songCell = tableView.dequeueReusableCellWithIdentifier("songCell", forIndexPath: indexPath) as! RecommendationCell
  
          songCell.recommendationThumbnail.image = recommendedImages[indexPath.row]
  
  
          return songCell
      }
  </code></pre>
  
  <hr>
  
  <p>Edit: My <code>numberOfRowsInSection</code> method. <code>recommendedTitles</code> is from the same block of code that I excluded. It's always going to be 6.</p>
  
  <pre><code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
          return recommendedTitles.count
      }
  </code></pre>