Skip to content

Instantly share code, notes, and snippets.

@timvermeulen
Created March 9, 2017 01:38
Show Gist options
  • Save timvermeulen/afd4a6aa4eb1cfc39fa8496673dc24af to your computer and use it in GitHub Desktop.
Save timvermeulen/afd4a6aa4eb1cfc39fa8496673dc24af to your computer and use it in GitHub Desktop.
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