UITableViewDiffableDataSource and UICollectionViewDiffableDataSource working different when class vs struct is used

138 Views Asked by At

I noticed, when using UITableViewDiffableDataSource / UICollectionViewDiffableDataSource, the ItemIdentifierType

when using

var managedDataSource: UITableViewDiffableDataSource<String, StringCellObject>!

class StringCellObject: Hashable {

    let value: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(value)
    }

    static func == (lhs: StringCellObject, rhs: StringCellObject) -> Bool {
        return lhs.value == rhs.value
    }

    init(value: String) {
        self.value = value
    }

}

when StringCellObject is a class, the Hashable functions are not even called and the objects are always treated as Changed (even the value is the same)

when i change the class to a struct

struct StringCellObject: Hashable {

i get the correct behavior

Why is there a change in behavior and how to get the expected behavior also when using classes?

1

There are 1 best solutions below

0
On

I think you have to implement Hashable method like below.

class Item: Hashable {
    
    static func == (lhs: Item, rhs: Item) -> Bool {
        lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    
    let id = UUID()
}