Contents

NSDiffableDataSourceSnapshot

A representation of the state of the data in a view at a specific point in time.

Declaration

struct NSDiffableDataSourceSnapshot<SectionIdentifierType, ItemIdentifierType> where SectionIdentifierType : Hashable, ItemIdentifierType : Hashable

Overview

Diffable data sources use snapshots to provide data for collection views and table views. You use a snapshot to set up the initial state of the data that a view displays, and you use snapshots to reflect changes to the data that the view displays.

The data in a snapshot is made up of the sections and items you want to display, in the order you that you determine. You configure what to display by adding, deleting, or moving the sections and items.

To display data in a view using a snapshot:

  1. Create a snapshot and populate it with the state of the data you want to display.

  2. Apply the snapshot to reflect the changes in the UI.

You can create and configure a snapshot in one of these ways:

  • Create an empty snapshot, then append sections and items to it.

  • Get the current snapshot by calling the diffable data source’s snapshot() method, then modify that snapshot to reflect the new state of the data that you want to display.

For example, the following code creates an empty snapshot and populates it with a single section with three items. Then, the code applies the snapshot, animating the UI updates between the previous state and the new state.

// Create a snapshot.
var snapshot = NSDiffableDataSourceSnapshot<Int, UUID>()        

// Populate the snapshot.
snapshot.appendSections([0])
snapshot.appendItems([UUID(), UUID(), UUID()])

// Apply the snapshot.
dataSource.apply(snapshot, animatingDifferences: true)

For more information, see the diffable data source types:

Bridging

You can bridge from an NSDiffableDataSourceSnapshotReference object to this type:

let snapshot = snapshotReference as NSDiffableDataSourceSnapshot<Int, UUID>

Topics

Creating a Snapshot

Getting Item and Section Metrics

Identifying Items and Sections

Inserting Items and Sections

Removing Items and Sections

Reordering Items and Sections

Reloading Data

Supporting Bridging

See Also

Data