Last active
March 6, 2022 09:59
-
-
Save chriseidhof/e45f401cd1eb7bf2da949004cff618b4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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