title: Swift 3: Caching images in a collectionView
body: <p>I'm currently working through my app, updating it to work with Swift 3 and have one problem left. Previously, my image caching worked really well, but since the update the <code>UIImageView</code>s aren't being populated when the image is fetched.</p>
  
  <p>Here is the code (in the <code>...cellForItemAt...</code> function):</p>
  
  <pre><code>if let img = imageCache[imageUrl] {
      print("CACHE HIT: \(indexPath)")
      cell.image.image = img
  } else {
      print("CACHE MISS: \(indexPath)")
      var imgUrl: = URL(string: imageUrl)
      let request: URLRequest = URLRequest(url: imgUrl!)
      let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -&gt; Void in
          if(data != nil) {
              print("IMAGE DOWNLOADED: \(imgUrl?.query))")
              let image = UIImage(data: data!) // create the image from the data
              self.imageCache[imageUrl] = image // Store in the cache
              DispatchQueue.main.async(execute: {
                  if let cell = collectionView.cellForItem(at: indexPath) as? MyCollectionViewCell {
                      print("APPLYING IMAGE TO CELL: \(indexPath)")
                      cell.image.image = image
                      self.collectionView.reloadData()
                  } else {
                      print("CELL NOT FOUND: \(indexPath)")
                  }
              })
          } 
      }) 
      dataTask.resume()
  }
  </code></pre>
  
  <p>As you can see, I've added in some <code>print</code>s to find out what is going on. When the view loads, I can see cache misses, and the images loading and the <code>UIImageView</code>s being populated for the visible rows, however when I scroll down, the <code>UIImageView</code>s are never populated, and the log shows <code>CELL NOT FOUND: [0, x]</code> for each indexPath. </p>
  
  <p>If I scroll up again after scrolling down, images are populated from the cache as expected.</p>
  
  <p>The code hasn't changed since the previous version of Swift / iOS / Xcode, and used to work perfectly.</p>
  
  <p>I'm not interested in any 3rd party extensions etc.; I want to understand what is wrong with the code above. Any other improvements/suggestions to the code however are welcome.</p>
  
  <p>Any ideas would be very much appreciated!</p>