Skip to content

Instantly share code, notes, and snippets.

@imthath-m
Created February 25, 2020 14:09
Show Gist options
  • Save imthath-m/c2fe723563752d6e18a17f3176b479c7 to your computer and use it in GitHub Desktop.
Save imthath-m/c2fe723563752d6e18a17f3176b479c7 to your computer and use it in GitHub Desktop.
Provide default implemenation for Equatable classes conforming to Codable
import Foundation
public extension Equatable where Self: Codable {
static func ==(lhs: Self, rhs: Self) -> Bool {
lhs.jsonData == rhs.jsonData
}
}
public extension Person: Equatable { }
func testEquatingCodables() {
var aslam = Person(name: "Aslam", age: 24)
var basith = Person(name: "Basith", age: 24)
var newPerson = Person(name: "Basith", age: 24)
print(aslam == basith) // false
print(basith == newPerson) // true
}
testEquatingCodables()
public extension Encodable {
public var jsonData: Data? {
return try? JSONEncoder().encode(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment