Getting an 'NSInternalInconsistencyException', reason: 'Invalid section 0.' when doing a search on multiple sections

I am getting an exception when doing a search on multiple section. It occurs when applying a snapshot on the datasource.

Background: I have (pre-defined) sections, and each section has a collection of items. Sections won't appear in the viewController if there are no items in section. Items are added by a function of the app. Once an item is added in one of the section, datasource update is called and will show the section with the item added.

Problem: Encountering this issue when trying to search for a non-existent item twice. To reproduce, you can enter a non-existent item, then delete the search string via a backspace, then input a non-existing item again, then error will be thrown on the dataSource.apply().
Hoping someone can help. TIA!

Here is the code:

Code Block
func updateData(on searchItem: String = "") {
snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
Manager.shared.getAllSections().forEach { section in
let items = section.items
//if search string is empty, we just assign the items of the section,
//else we filter it based on the searchItem
var filteredItems = searchItem.isEmpty ? items :
items.filter { $0.itemName.lowercased().contains(searchItem.lowercased()) }
//if theres no items filtered, we ain't appending any section and items
if filteredItems.count > 0 {
snapshot.appendSections([section])
snapshot.appendItems(filteredItems)
}
}
//I get the exception when calling apply on dataSource
dataSource.apply(snapshot, animatingDifferences: false)
}
//Here is the updateSearchResults delegate method triggered when typing something in the search bar
func updateSearchResults(for searchController: UISearchController) {
guard let searchedItem = searchController.searchBar.text, !searchedItem.isEmpty else {
updateData()
return
}
updateData(on: searchedItem)
}


snapShot is created empty on line 3.

so, if test line 15 fails (no filtered items), you apply() an empty datasource.
I assume (couyld not find doc here) that's not allowed.
So you should test before apply().

May have a look here on some other specifics for apply().
https://stackoverflow.com/questions/58792252/appending-sections-in-nscollectionviewdiffabledatasource
Hey @Claude31, thanks for the reply. yeah, you're right. I am not appending anything in the snapshot if the filtered item is empty. That somehow causes the issue.

I did already try to append the section and items (even if the items are empty), and there's no exception thrown. However, sections will show without any item, and I don't like that. It will look like the AppStore app with the pictures of the app but the space is allocated.

What I want is, the section shouldn't show if there are no item for that particular section. :)
Getting an 'NSInternalInconsistencyException', reason: 'Invalid section 0.' when doing a search on multiple sections
 
 
Q