Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Last active March 6, 2022 09:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/e45f401cd1eb7bf2da949004cff618b4 to your computer and use it in GitHub Desktop.
Save chriseidhof/e45f401cd1eb7bf2da949004cff618b4 to your computer and use it in GitHub Desktop.
// Simplified version of https://gist.github.com/anandabits/d9494d14fef221983ff4f1cafa318d47#file-areequatablyequal-swift
func isEqual(x: Any, y: Any) -> Bool {
func f<LHS>(_ lhs: LHS) -> Bool {
let p = Wrapper<LHS>.self as? AnyEquatable.Type
return p?.isEqual(x, y) ?? false
}
return _openExistential(x, do: f)
}
private protocol AnyEquatable {
static func isEqual(_ lhs: Any, _ rhs: Any) -> Bool
}
private enum Wrapper<T> {}
extension Wrapper: AnyEquatable where T: Equatable {
static func isEqual(_ lhs: Any, _ rhs: Any) -> Bool {
guard let l = lhs as? T, let r = rhs as? T else { return false }
return l == r
}
}
print(isEqual(x: [5,6,7] as Any, y: [5,6,7] as Any))
@ollieatkinson
Copy link

With a small adaptation you can also make this work for heterogenous containers like [String: Any] and [Any] which are typically used to represent JSON structures. https://gist.github.com/ollieatkinson/9fa246abf21a09a52d7c7c6e6149dc1e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment