多分区多对象Diffable Data Source:如何同时获取分区与项类型?
同时获取Diffable Data Source的分区类型与项类型的简洁实现方式
你当前的Diffable Data Source在cellProvider中只能单独访问项类型(item),需额外通过indexPath获取分区类型,导致多次switch判断的冗余逻辑。可以通过合并分区类型与项类型进行联合判断的方式简化实现,同时直接获取项的关联数据,避免重复操作。
你的数据模型代码
enum BrowseSectionType: Hashable { case featured case latest case popular case expiring case link } struct BrowseSection: Hashable { var section: BrowseSectionType var title: String? var subtitle: String? var items: [BrowseItem] } enum BrowseItem: Hashable { case discount(DiscountItem) case link(LinkItem) } enum LinkItemType: Hashable { case category case saved } struct LinkItem: Hashable { var item: LinkItemType var text: String }
优化后的数据源实现
fileprivate func setUpDataSource() { dataSource = BrowseDataSource(collectionView: collectionView, cellProvider: { [weak self] (collectionView, indexPath, item) -> UICollectionViewCell? in guard let self = self else { return UICollectionViewCell() } let sectionType = self.sections[indexPath.section].section // 联合判断分区类型与项类型,一次switch处理所有场景 switch (sectionType, item) { case (.featured, .discount(let discountItem)): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LargeDiscountCell.identifier, for: indexPath) as! LargeDiscountCell cell.configure(with: discountItem) return cell case (.latest, .discount(let discountItem)), (.expiring, .discount(let discountItem)): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MediumDiscountCell.identifier, for: indexPath) as! MediumDiscountCell cell.configure(with: discountItem) return cell case (.popular, .discount(let discountItem)): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SmallDiscountCell.identifier, for: indexPath) as! SmallDiscountCell cell.configure(with: discountItem) return cell case (.link, .link(let linkItem)): let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LinkCell.identifier, for: indexPath) as! LinkCell cell.configure(with: linkItem) return cell // 处理未匹配的组合(可选,根据业务需求调整) default: return UICollectionViewCell() } }) }
额外优化建议
- 给每个Cell添加
configure(with:)方法,将配置逻辑从cellProvider中剥离,让数据源代码更简洁,符合单一职责原则。 - 若后续分区与项的组合逻辑更复杂,可将「分区类型+项类型」的映射逻辑封装到单独工具类或枚举中,进一步解耦。
内容的提问来源于stack exchange,提问作者David Henry
相关产品推荐
相关产品推荐

