简体   繁体   中英

Hashable == method does not detect difference between two objects swift

I implemented the class below:

    class Table : Hashable {

    var uid : Int
    var timeRemaining : Int?
    var currentPrice : Double?
    var hashValue: Int {
        return uid.hashValue
    }

    static func ==(lhs: Table, rhs: Table) -> Bool {
        return lhs.uid == rhs.uid && lhs.timeRemaining == rhs.timeRemaining && lhs.currentPrice == rhs.currentPrice
    }

    init (uid: Int, timeRemaining: Int?, currentPrice: Double?) {
        self.uid = uid
        self.timeRemaining = timeRemaining
        self.currentPrice = currentPrice
    }
}

I've also defined an array of objects of this class:

private var tables = [Table]()

Next, I have the following method which runs every second:

func updateAuctions() {
    let oldItems = tables
    let newItems = oldItems
    for table in newItems {
        let oldPrice = table.currentPrice!
        let timeRemaining = table.timeRemaining!
        table.currentPrice = oldPrice + 0.50
        table.timeRemaining = timeRemaining - 1
    }
    let changes = diff(old: oldItems, new: newItems)

    collectionView.reload(changes: changes, section: 0) { (complete) in
        if (complete) {
            self.tables = newItems
        }
    }
}

This uses the DeepDiff framework described here: https://github.com/onmyway133/DeepDiff

My goal is to refresh the UICollectionView with the changes made to the tables array, however no changes are detected by the framework, even though my == method checks that the timeRemaining and currentPrice match.

let newItems = oldItems

Since both array contain object instances, wouldn't they just point to the same objects? So when you iterate through newItems and changing values, you are essentially changing values of oldItems too. You can verify this by printing the values of both array after the for loop.

Maybe you can try something similar to the following?

func updateAuctions() {
    let oldItems = tables
    let newItems = [Table]()
    for item in oldItems {
        newItems.append(Table(uid: item.uid, timeRemaining: item.timeRemaining! - 1, currentPrice: item.currentPrice! + 0.50))
    }
    let changes = diff(old: oldItems, new: newItems)

    collectionView.reload(changes: changes, section: 0) { (complete) in
        if (complete) {
            self.tables = newItems
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM