UICollectionViewDiffableDataSource - 具有不同散列的相同项目时崩溃

Jos*_* B. 7 uikit uicollectionview swift uicollectionviewdiffabledatasource

我用来UICollectionViewDiffableDataSource填充UICollectionView数据。我的理解是,DiffableDataSource通过使用来比较项目==,然后如果项目相等,它会比较hash值以查看是否发生了变化。

但根据我得到的错误,情况并非如此。

Diffable data source detected item identifiers that are equal but have different hash values. Two identifiers which compare as equal must return the same hash value. You must fix this in the Hashable (Swift) or hash property (Objective-C) implementation for the type of these identifiers
Run Code Online (Sandbox Code Playgroud)

就我而言,我有与 uniqueID 进行比较的项目,并且 hashValue 由用户输入的值确定。如果 == 和 hashValue 不能不同,那么使用它们有什么意义呢?

hst*_*tdt 0

解决方法:通过 hashValue 和 uniqueID 进行相等以避免equal but have different hash values崩溃。

static func == (lhs: Item, rhs: Item) -> Bool {
   lhs.hashValue == rhs.hashValue && lhs.id == rhs.id
}
Run Code Online (Sandbox Code Playgroud)

也许不是一个完美的解决方案。就我而言,我只需要==移动动画,因此当只有一项更改并需要移动时,我通过通知发送更改的值,并在动画后替换项目:

dataSource.apply(snapshot, animatingDifferences: true) { [weak self] in
    guard let self else { return }
    snapshot.insertItems([newItem], beforeItem: item)
    snapshot.deleteItems([item])
    snapshot.reconfigureItems([newItem])
    dataSource.apply(snapshot, animatingDifferences: false)
}
Run Code Online (Sandbox Code Playgroud)

非常同意“如果 == 和 hashValue 不能不同,那么使用它们有什么意义”:)