Created
March 9, 2017 01:38
-
-
Save timvermeulen/afd4a6aa4eb1cfc39fa8496673dc24af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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