I made a collection view with diffable data source. The snapshot is defined as :
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
Section is declared as:
struct Section:Hashable {
let title: String
let items: [String]
}
In view controller:
let sections = [Section(title: "morning", items: ["Item 1", "Item 2"]),
Section(title: "noon", items: ["Item 3", "Item 4"])]
snapshot.appendSections(sections)
for section in sections {
snapshot.appendItems(section.items, toSection: section)
}
My question is in view controller the section has already items why again we have to append items with appendItems(...) in order this to work. I tried Apple documentation and didn't quite understood why.
You had to use
appendItemsto "append the items again" becauseappendSectionjust adds a section, not the items.The two type parameters of
NSDiffableDataSourceSnapshotare just identifiers for the sections and items. Importantly, the section identifier doesn't need to contain all the items in that section - it's just something that identifies that section. You can think of this as a "name" for that section.Based on your
Sectionstruct, I would useStringas the section identifier:The section identifiers can be the
titles of theSections.While it is technically possible to use
Sectionitself as the section identifier (i.e. a section's "name" is itstitlecombined with all its items), this is undesirable most of the time.These identifiers help the data source figure out what to animate, when you
applya snapshot. The diffable data source finds the difference between the existing snapshot and the new snapshot you applied.If you use the sections' items as the section identifier, that means every time an item is added/removed/changed, that section's identifier changes. That means the section with the old identifier is removed, and a new section with the new identifier is added. The data source would animate the removal of that whole section, and the insertion of a new section in its place.
If only the section's
titleis the identifier, the data source would know that the section hasn't changed, and it will only animate the insertion/removal/change of that particular item. While the end results are the same, the animations are very different.