Skip to content

Instantly share code, notes, and snippets.

@chosa91
Forked from chriseidhof/anyequatable.swift
Last active August 6, 2021 13:22
Show Gist options
  • Save chosa91/d945762fb3f234421575f452c14ac016 to your computer and use it in GitHub Desktop.
Save chosa91/d945762fb3f234421575f452c14ac016 to your computer and use it in GitHub Desktop.
import Foundation
struct AnyEquatable {
private let isEqualTo: (Any) -> Bool
let value: Any
init<A: Equatable>(_ value: A) {
self.value = value
isEqualTo = { other in
guard let o = other as? A else { return false }
return value == o
}
}
}
extension AnyEquatable: Equatable {
static func ==(lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
return lhs.isEqualTo(rhs.value)
}
}
let x = AnyEquatable(5)
let y = AnyEquatable("hello")
x == y
AnyEquatable(4) == AnyEquatable(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment