Skip to content

Instantly share code, notes, and snippets.

@philosopherdog
Last active October 13, 2021 16:28
Show Gist options
  • Save philosopherdog/a7f2c6a4ebe312f0fc5ca91c8920b951 to your computer and use it in GitHub Desktop.
Save philosopherdog/a7f2c6a4ebe312f0fc5ca91c8920b951 to your computer and use it in GitHub Desktop.
Equatable Type Erasure
protocol Equating {
func isEqualTo(_ other: Equating)-> Bool
}
extension Equating where Self: Equatable {
func isEqualTo(_ other: Equating) -> Bool {
guard let other = other as? Self else { return false }
return other == self
}
}
/* Examples */
struct Person: Equating & Equatable {
let name: String
let age: Int
}
struct Favourites: Equating & Equatable {
let color: UIColor
var person: Person? = nil
}
extension Favourites {
init(color: UIColor, person: Person) {
self.color = color
self.person = person
}
}
Person(name: "fred", age: 22).isEqualTo(Person(name: "Frank", age: 33))
Person(name: "fred", age: 22).isEqualTo(Person(name: "fred", age: 22))
Person(name: "fred", age: 22).isEqualTo(Favourites(color: .red))
Favourites(color: .black, person: Person(name: "x", age: 12)).isEqualTo(Favourites(color: .black))
Favourites(color: .black, person: Person(name: "x", age: 12)).isEqualTo(Favourites(color: .black, person: Person(name: "x", age: 12)))
Favourites(color: .green).isEqualTo(Favourites(color: .black))
let examples: [Equating] = [
Person(name: "fred", age: 22),
Person(name: "Frank", age: 33),
Favourites(color: .red),
Favourites(color: .red)
]
for idx in 1..<examples.count {
let result = examples[idx-1].isEqualTo(examples[idx])
print(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment