title: UICollection View Cell is mixing up when i scroll
body: <p>I am having a problem with cells in a UICollectionView where images are mixing up when scrolling up or down. It will mix up and then stay mixed up, or it will go back to the correct order.</p>
  
  <pre><code>class booksVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
      var imageIdsonDB : [String] = []
      var imageIds : [String] = []
  
      @IBOutlet weak var collectionView: UICollectionView!
  
      var posts = [Post]()
      let db : DBHelper = DBHelper()
      var arrayBooks = [BookModel]()
      var selectedIndexPath : IndexPath = IndexPath()
      var post: Post!
  
      override func viewDidLayoutSubviews() {
          adjustViewLayout(size: UIScreen.main.bounds.size)
      }
  
      override func viewDidLoad() {
          super.viewDidLoad()
          collectionView.delegate = self
          collectionView.dataSource = self
          for item in self.db.fetchAll() {
              imageIdsonDB.append(item.id)
          }
  
          self.arrayBooks.removeAll()
          self.arrayBooks.append(contentsOf: self.db.fetchAll())
          self.collectionView.reloadData()
  
          DataService.ds.REF_POSTS8.observe(.value, with: { (snapshot) in
  
              if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                  for snap in snapshot {
                      print ("SNAP: \(snap)")
                      if let postDict = snap.value as? Dictionary&lt;String, AnyObject&gt;{
                          let key = snap.key
                          let post = Post(postKey: key , postData: postDict)
                          self.posts.append(post)
                          self.db.insertBook(id: postDict["id"] as! String, imgName: postDict["id"] as! String, imgPath: "", bookName: postDict["book_name"] as! String, bookPath: "", imageURL: postDict["image_path"] as! String, bookURL: postDict["book_path"] as! String, caption: "")
                      }
                  }
              }
              self.arrayBooks.removeAll()
              self.arrayBooks.append(contentsOf: self.db.fetchAll())
              self.collectionView.reloadData()
          })
          // update db for changed database data
          for image in self.db.fetchAll() {
              if !self.imageIds.contains(image.id) {
                  self.db.deleteBook(id: image.id)
              }
          }
          self.collectionView.reloadData()
      }
      func getFilePath(name : String) -&gt; String {
          let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
          let filePath = documentsPath+"/"+name
          return filePath
      }
  
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
          return arrayBooks.count
      }
  
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
          let book = arrayBooks[indexPath.item]
          if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)as? collectionViewCellBooks {
              SwiftLoader.hide()
              cell.initWithBook(book: book)
              return cell
          } else {
              return collectionViewCellBooks()  
          } 
      }
  
      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
          self.selectedIndexPath = indexPath
          self.performSegue(withIdentifier: "showImage", sender: self)
      }
      override func prepare(for segue: UIStoryboardSegue, sender: Any?)
      { 
          if segue.identifier == "showImage"
          {
              let vc = segue.destination as! showPdfVC
              vc.book = self.arrayBooks[self.selectedIndexPath.row]
          }
      } 
  }
  </code></pre>
  
  <p>The code for <code>initwithBook</code> function is </p>
  
  <pre><code>func initWithBook(book : BookModel) {
      self.caption.text = book.bookName
      if book.thumbImagePaht == "" {
          let ref = FIRStorage.storage().reference(forURL: book.imageURL)
         let downloadTask =  ref.data(withMaxSize: 4 * 1024 * 1024, completion: { (data,error) in
              if error != nil {    
              }else {
                  if let imgData = data {
                      if let img = UIImage(data: imgData) {
                          self.imageView.image = img
                          let imageName = book.id+".jpg"
                          let filepath = self.getFilePath(name: imageName)
                          if (try? data?.write(to: URL(fileURLWithPath: filepath),options: [.atomic])) != nil {
                              self.db.upDateImagePath(id: book.id, imagePath: filepath)
                          }
                          self.stopLoading();
                      }
                  }
              }
          })
          downloadTask.observe(.progress) { (snapshot) -&gt; Void in
              // Download reported progress
  
              let percentComplete = 100 * Double(snapshot.progress!.completedUnitCount)
                  / Double(snapshot.progress!.totalUnitCount)
  
              print(percentComplete)
              // Update the progress indicator
          }
  
          downloadTask.observe(.success) { (snapshot) -&gt; Void in
              // Download completed successfully
              print("Download Success")
          } 
      } else {
          let image = UIImage(contentsOfFile: book.thumbImagePaht)
          self.imageView.image = image
          stopLoading();
      }
  )
  </code></pre>