I have a collection view with multiple sections and eventually multiple cell types. I've read that we should avoid using indexPath with using diffable data sources. Is the way I currently access sections defeat the purpose of using diffable data sources?
private func generateLayout() -> UICollectionViewLayout {
let sectionProvider = { [weak self] (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
guard let self = self else { return nil }
guard self.dataController.sections.indices.contains(sectionIndex) else { return nil }
let section: NSCollectionLayoutSection
let sectionKind = self.dataController.sections[sectionIndex] // This is the line in question
switch sectionKind {
case .food:
var configuration = UICollectionLayoutListConfiguration(appearance: .plain)
section = NSCollectionLayoutSection.list(using: configuration, layoutEnvironment: layoutEnvironment)
}
let headerFooterSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.8461538462),
heightDimension: .estimated(26.0)
)
let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerFooterSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .top
)
section.boundarySupplementaryItems = [sectionHeader]
return section
}
return UICollectionViewCompositionalLayout(sectionProvider: sectionProvider)
}
private func generateDataSource() -> UICollectionViewDiffableDataSource<HomeDataController.Section, Item> {
let itemCellRegistration = setupItemCellRegistration()
let headerRegistration = setupHeaderRegistration()
let dataSource = UICollectionViewDiffableDataSource<HomeDataController.Section, Item>(collectionView: collectionView) { [weak self] collectionView, indexPath, item in
guard let self = self else { return nil }
guard self.dataController.sections.indices.contains(indexPath.section) else { return nil }
let sectionKind = self.dataController.sections[indexPath.section] // This is the line in question
switch sectionKind {
case .gear:
return collectionView.dequeueConfiguredReusableCell(using: itemCellRegistration, for: indexPath, item: item)
}
}
dataSource.supplementaryViewProvider = { collectionView, kind, indexPath in
guard kind == UICollectionView.elementKindSectionHeader else { return nil }
return collectionView.dequeueConfiguredReusableSupplementary(using: headerRegistration, for: indexPath)
}
return dataSource
}