skip to content

In UIKit, how do you drive a UICollectionView with UICollectionViewDiffableDataSource and NSDiffableDataSourceSnapshot, and what must the item identifiers be?

level: middleimportance: must knowfreq 70%

answer

  1. state in, diff out
  2. cell provider plus registration
  3. append sections, append items, apply
  4. unique, Hashable, stable

basics

~20 s

Create a UICollectionViewDiffableDataSource with a cell provider, build an NSDiffableDataSourceSnapshot of section and item identifiers, and call apply(_:animatingDifferences:); UIKit diffs it against what is shown. Identifiers must be unique, Hashable and stable, ideally each model's ID.

solid answer

~50 s

Since iOS 13 a diffable data source replaces the index-path methods: `init(collectionView:cellProvider:)` takes a closure that returns a cell for an index path and item identifier, and the object implements `UICollectionViewDataSource` for you. To show data, build a snapshot with `appendSections(_:)` and `appendItems(_:toSection:)`, or take the current one with `snapshot()` and change it, then call `apply(_:animatingDifferences:)`; the data source computes the difference in O(n) and performs the inserts, deletes and moves, so there is no hand-written `performBatchUpdates` bookkeeping. Identifiers must be unique Hashable values: duplicates in one append raise an exception, and Apple recommends structs or enums (a class must subclass `NSObject`). Use the model's stable ID, look the model up in a `UICollectionView.CellRegistration` created once, keep the data source in a stored property because `dataSource` is weak, and never swap the collection view's data source afterwards.

code

swift · 28 lines
swift
import UIKit

struct Listing: Identifiable { let id: UUID; var address: String; var price: String }
enum Section: Hashable { case listings }

@MainActor
func makeDataSource(for collectionView: UICollectionView,
                    listing: @escaping (Listing.ID) -> Listing?) -> UICollectionViewDiffableDataSource<Section, Listing.ID> {
    // Created once, outside the cell provider; the handler looks the model up by its ID.
    let registration = UICollectionView.CellRegistration<UICollectionViewListCell, Listing.ID> { cell, _, id in
        guard let listing = listing(id) else { return }
        var content = cell.defaultContentConfiguration()
        content.text = listing.address
        content.secondaryText = listing.price
        cell.contentConfiguration = content
    }
    return UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, id in
        collectionView.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: id)
    }
}

@MainActor
func show(_ listings: [Listing], in dataSource: UICollectionViewDiffableDataSource<Section, Listing.ID>) {
    var snapshot = NSDiffableDataSourceSnapshot<Section, Listing.ID>()
    snapshot.appendSections([.listings])
    snapshot.appendItems(listings.map(\.id), toSection: .listings)
    dataSource.apply(snapshot, animatingDifferences: true)
}

go deeper

for a junior

Recall the pieces: a diffable data source with a cell provider, a snapshot of sections and items, and apply.

for a middle

Explain how the diff uses identity, why identifiers must be unique and stable, what animatingDifferences false still does, and why the registration is created once.

for a senior

Spot identifier choices that turn updates into delete-and-insert, data sources released by the weak property, and queue mixing when snapshots are applied from several places.

for a principal

Weigh diffable data sources as the team default against the index-path API, including diff cost on very large lists and what old screens should keep.

## From index paths to identifiers A classic data source answers questions by **index path**: how many items in section 2, which cell for item 7. When data changes you must describe the change yourself with `performBatchUpdates(_:completion:)`, and if the counts you report afterwards disagree with the edits, UIKit raises an exception. A **diffable data source** (iOS 13) turns this around. You describe the *whole current state* as a **snapshot**, a value listing section identifiers and the item identifiers in each, and the data source works out the difference from what is on screen and animates it. ## The four steps Apple's documentation for `UICollectionViewDiffableDataSource` lists the steps: 1. **Connect** a diffable data source to the collection view with `init(collectionView:cellProvider:)`. 2. **Implement a cell provider**, the closure that receives the collection view, an index path and an item identifier and returns a cell. 3. **Generate the current state** of the data as an `NSDiffableDataSourceSnapshot`: `appendSections(_:)`, then `appendItems(_:toSection:)`. 4. **Display it** with `apply(_:animatingDifferences:)`. For later changes you either build a fresh snapshot from the model or call `dataSource.snapshot()`, mutate it with `insertItems`, `deleteItems`, `moveItem` and similar methods, and apply it again. Inside the provider, the usual pattern since iOS 14 is `dequeueConfiguredReusableCell(using:for:item:)` with a `UICollectionView.CellRegistration`, which registers the cell type for you. The documentation warns against creating that registration inside the provider closure: doing so prevents cell reuse and generates an exception in iOS 15 and higher. ## Choosing item identifiers The diff works on **identity**, so the identifier type decides what counts as "the same item": - Identifiers must be **unique** across the snapshot's items (sections are a separate space). The header says that passing duplicate values throws an exception. - They must be **Hashable**, and the documentation recommends `struct` or `enum` value types such as `Int`, `String` or `UUID`; a class identifier must be an `NSObject` subclass. - They should be **stable**: the same listing yields the same identifier in every snapshot. Use `Listing.ID`, not the index, and not a value that changes when a price changes. | Identifier | What a price change does | |---|---| | The listing's ID | same item; you signal the new content with `reconfigureItems(_:)` | | The whole `Hashable` listing struct | a different value, so the diff removes the old item and inserts a new one | | A position such as the row number | identity shifts on every insert, so the diff reports the wrong changes | Keep the models in a dictionary or store, and have the registration handler look each one up by ID. ## Applying snapshots | Call | Behaviour | |---|---| | `apply(_:animatingDifferences: true)` | diffs and animates the changes; the completion runs on the main queue | | `apply(_:animatingDifferences: false)` | the header says it still diffs, but applies without animation | | `applySnapshotUsingReloadData(_:)` (iOS 15) | skips diffing and resets the view at once, for a completely different data set or an exceptionally large change | The header allows applying from a background queue as long as every apply for that data source uses the same queue, and it logs or asserts if you mix them. In Swift the methods are declared `@MainActor`, so most apps simply apply on the main actor. ## Updating one section at a time Since iOS 14 a collection view's diffable data source can also take an `NSDiffableDataSourceSectionSnapshot` for a single section through `apply(_:to:animatingDifferences:)`, and `snapshot(for:)` returns the current one. That suits a screen where one section changes on its own schedule, such as a row of saved searches refreshed separately from the listings, and section snapshots are also how expandable, outline-style items are described. ## Tables use the same model `UITableViewDiffableDataSource` works the same way with `init(tableView:cellProvider:)` and the same snapshot type. Table views have no cell registration type, so you register a cell class up front and the provider calls `dequeueReusableCell(withIdentifier:for:)`. Header titles come from subclassing the data source and overriding `tableView(_:titleForHeaderInSection:)`. ## Pitfalls - A data source held only in a local variable: the collection view's `dataSource` property is weak, so the list goes empty. - Reassigning `collectionView.dataSource` after attaching a diffable one; the documentation says to create a new collection view and data source instead. - Building the registration inside the provider closure. - Using whole models as identifiers, so every content change becomes a delete and an insert.

  • How does a UITableView use the same pattern?
    `UITableViewDiffableDataSource` (iOS 13) takes a table view and a cell provider and applies the same `NSDiffableDataSourceSnapshot`. Tables have no `CellRegistration`, so you register a cell class for a reuse identifier and call `dequeueReusableCell(withIdentifier:for:)` inside the provider. Section header titles come from a subclass that overrides `tableView(_:titleForHeaderInSection:)`.
  • Why must the cell registration not be created inside the cell provider?
    Apple's documentation says a registration created in the provider closure prevents cell reuse and generates an exception in iOS 15 and higher. Create it once, before building the data source or as a stored property, and let the provider capture it.
  • When is applySnapshotUsingReloadData(_:) the right call?
    It arrived in iOS 15 and skips the diff, resetting the view to the snapshot immediately and without animation. The header suggests it for reusing a collection view with a completely different data set, or for an exceptionally large change where you want to skip diffing.

  • The whole model struct is the best item identifier because cells then need no lookup.
  • Passing false for animatingDifferences skips the diff and reloads everything.
  • Appending a duplicate identifier just shows two cells for the same item.
  • You can swap in a custom dataSource later, for example while the screen is editing.
  • A snapshot must be built by recording each insert and delete, like batch updates.