Table and collection view cell reuse

UIKit Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Spot the bug

While scrolling fast, rows briefly show other rows' photos. Tap the line that causes it.

  1. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  2. let cell = tableView.dequeueReusableCell(withIdentifier: "Photo", for: indexPath) as! PhotoCell
  3. let item = items[indexPath.row]
  4. cell.titleLabel.text = item.title
  5. ImageLoader.shared.load(item.url) { image in
  6. cell.photoView.image = image
  7. }
  8. return cell
  9. }
Hint 1 of 1

By the time the image arrives, which row does this cell show?

Choose an answer, then open Show answer below to check it.

Show answer
  • Answer: line 6 cell.photoView.image = image

Line 6 sets the image on whatever row the reused cell shows by the time the load finishes. Save cell.itemID = item.id, check it in the completion, clear the image in prepareForReuse and cancel the old load.

30-second answer

Lists create only enough cells for the screen and reuse them as you scroll: dequeueReusableCell returns a recycled cell that may still show old content. Reset state in prepareForReuse or fully configure every cell. When images load asynchronously, check that the cell still shows the same item before applying the result.

Practise saying it · 45 s. No recording, just a timer

Explain cell reuse and the wrong-image bug.

Say your answer out loud, then check which of these points you covered:

  • Cells are recycled
  • Reset in prepareForReuse
  • Check identity before applying async results

Deep dive

Store the item's id on the cell and compare in the completion.

Cancel the image task in prepareForReuse.

Cell registrations and content configurations (iOS 14+) reduce reuse bugs.

Prefetching (UITableViewDataSourcePrefetching) starts loads early.

Common mistakes

  • Applying async results to whatever cell captured the closure.
  • Configuring only some properties per row.

Senior take & follow-ups

Seniors explain why the bug appears only while scrolling fast, and fix it with identity checks.

Follow-up questions

Think of your answer first, then open the hint.

  1. What belongs in prepareForReuse?

    Show hint

    Resetting transient state and cancelling work, not full configuration.

  2. How do diffable data sources help?

    Show hint

    They reconfigure cells by item identity.

Suggest a fix if something here is wrong or out of date.