Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
extension String {
init<T>(dumping x: T) {
self.init()
dump(x, to: &self)
}
}
func assertDumpsEqual<T>(_ lhs: @autoclosure () -> T, _ rhs: @autoclosure () -> T, file: StaticString = #file, line: UInt = #line) {
assert(String(dumping: lhs()) == String(dumping: rhs()), "Expected dumps to be equal.", file: file, line: line)
}
protocol DumpEquatable: Equatable {
static func areEqual(_ lhs: Self, _ rhs: Self) -> Bool
}
extension DumpEquatable {
static func == (lhs: Self, rhs: Self) -> Bool {
let areProbablyEqual = areEqual(lhs, rhs)
if areProbablyEqual {
assertDumpsEqual(lhs, rhs)
}
return areProbablyEqual
}
}
// Example:
struct Person {
var name: String
var age: Int
}
extension Person: DumpEquatable {
static func areEqual(_ lhs: Person, _ rhs: Person) -> Bool {
return lhs.name == rhs.name
}
}
let alice1 = Person(name: "Alice", age: 23)
let alice2 = Person(name: "Alice", age: 39)
alice1 == alice2 // assertion failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment