Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DiffableDataSource with multiple cell types

I'm looking at DiffableDataSource available in iOS13 (or backported here: https://github.com/ra1028/DiffableDataSources) and cannot figure out how one would support multiple cell types in your collection or tableview.

Apple's sample code1 has:

var dataSource: UICollectionViewDiffableDataSource<Section, OutlineItem>! = nil

which seems to force a data source to be a single cell type. If I create a separate data source for another cell type - then there is no guarantee that both data sources don't have apply called on them at the same time - which would lead to the dreaded NSInternalInconsistencyException - which is familiar to anyone who has attempted to animate cell insertion/deletion manually with performBatchUpdates.

Am I missing something obvious?

like image 623
Jason Moore Avatar asked Aug 14 '19 15:08

Jason Moore


1 Answers

I wrapped my different data in an enum with associated values. In my case, my data source was of type UICollectionViewDiffableDataSource<Section, Item>, where Item was

enum Item: Hashable {
  case firstSection(DataModel1)
  case secondSection(DataModel2)
}

then in your closure passed into the data source's initialization, you get an Item, and you can test and unwrap the data, as needed.

(I'd add that you should ensure that your backing associated values are Hashable, or else you'll need to implement that. That is what the diff'ing algorithm uses to identify each cell, and resolve movements, etc)

like image 131
oflannabhra Avatar answered Oct 20 '22 19:10

oflannabhra