DiffableDataSource는 Apple이 iOS 13부터 도입한 새로운 방식의 데이터 소스 관리 API로, 기존 UITableViewDataSource나 UICollectionViewDataSource의 복잡한 업데이트 로직을 간결하고 안전하게 대체합니다.
기존에는 UITableView 또는 UICollectionView에서 데이터를 갱신할 때 다음과 같은 작업이 필요했습니다:
insertRows, deleteRows, reloadRows 등을 직접 계산하여 호출DiffableDataSource는 스냅샷(Snapshot) 기반으로 작동합니다. UI에 표시할 데이터의 상태를 하나의 snapshot으로 정의하고, 해당 snapshot을 적용(apply)하면 내부적으로 알아서 diff(차이)를 계산하여 UI를 자동으로 갱신합니다.
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.main])
snapshot.appendItems([item1, item2, item3])
dataSource.apply(snapshot, animatingDifferences: true)
NSDiffableDataSourceSnapshotUICollectionViewDiffableDataSource / UITableViewDiffableDataSourceHashable을 준수해야 함enum Section {
case main
}
struct Item: Hashable {
let id: UUID
let title: String
}
let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) {
(collectionView, indexPath, item) -> UICollectionViewCell? in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
cell.textLabel.text = item.title
return cell
}
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.main])
snapshot.appendItems([Item(id: UUID(), title: "Hello")])
dataSource.apply(snapshot, animatingDifferences: true)
Hashable을 정확히 구현해야 함DiffableDataSource는 UI 갱신을 선언적으로 처리할 수 있게 해주며, 코드의 유지보수성과 안정성을 크게 향상시킵니다. iOS 13 이상을 타겟으로 한다면 적극 사용하는 것이 좋습니다.