onmyway133 / DeepDiff

🦀Amazingly incredible extraordinary lightning fast diffing in Swift
https://onmyway133.com/apps/
Other
2.05k stars 143 forks source link

How to use diffId when diffing SQL entities? #55

Closed munibrahman closed 4 years ago

munibrahman commented 4 years ago

Hi, I am trying to use DeepDiff and my models are sql objects that are returned from my backend. To enable the use of deepdiff, I need to be able to return a diffId in the to conform to the protocol DiffAware.

The problem arises that my sql objects have composite primary keys, meaning that it requires more than just one element to compare each object's uniqueness. It is easy to do checks in the compareContent function, but I am very puzzled to how one would go about declaring the diffId to ensure that these types can return a hash, and that being a string has since all of my attributes are composed of strings.

An example object is instantiated like Object(place: String, date: String, time: String, reason: String). Where the primary key is composed of the place, date and time values. How would one go about setting the diffId for this object?

I hope this example makes sense.

Thank you.

github-actions[bot] commented 4 years ago

Message that will be displayed on users' first issue

munibrahman commented 4 years ago

Figured it out. Will share solution tomorrow. Issue can be closed.

Edit: In swift you must implement the Equatable, Hashable and Diffaware protocols like below.

extension Object: Equatable, Hashable, DiffAware {
    public static func == (lhs: Object, rhs: Object) -> Bool {
        return lhs.place == rhs.place && lhs.date == rhs.date && lhs.time == rhs.time
    }
    public func hash(into hasher: inout Hasher) {
        hasher.combine(place)
        hasher.combine(date)
        hasher.combine(time)
    }

    public var diffId: Int {
        return hashValue
    }

    public static func compareContent(_ a: Object, _ b: Object) -> Bool {
        return a.place == b.place && a.date == b.date && a.time == b.time
    }
}
onmyway133 commented 4 years ago

@returnzer0 Hi, glad you sorted it out. Looking forward to seeing your solution