Reputation: 31
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.
Upvotes: 0
Views: 449
Reputation: 270758
You had to use appendItems
to "append the items again" because appendSection
just adds a section, not the items.
The two type parameters of NSDiffableDataSourceSnapshot
are 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 Section
struct, I would use String
as the section identifier:
var snapshot = NSDiffableDataSourceSnapshot<String, String>()
The section identifiers can be the title
s of the Section
s.
let sections = [...]
snapshot.appendSections(sections.map(\.title))
for section in sections {
snapshot.appendItems(section.items, toSection: section.title)
}
While it is technically possible to use Section
itself as the section identifier (i.e. a section's "name" is its title
combined with all its items), this is undesirable most of the time.
These identifiers help the data source figure out what to animate, when you apply
a 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 title
is 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.
Upvotes: 1