Skip to content

Instantly share code, notes, and snippets.

@dungntm58
Created November 13, 2022 16:36
Show Gist options
  • Save dungntm58/6f88221dc2ae5703de932e3f3d08fefb to your computer and use it in GitHub Desktop.
Save dungntm58/6f88221dc2ae5703de932e3f3d08fefb to your computer and use it in GitHub Desktop.
Compare two values of type Any
// From Swift 5.7 onwards, in Xcode 14, we can compare two values of type Any
// as we can cast values to any Equatable and use any Equatable as a parameter type as well
// thanks to Unlock existentials for all protocols change.
// Refer: https://github.com/apple/swift-evolution/blob/main/proposals/0309-unlock-existential-types-for-all-protocols.md
private extension Equatable {
func isEqual(_ other: any Equatable) -> Bool {
guard let other = other as? Self else {
return false
}
return self == other
}
}
func areEqual(first: Any?, second: Any?) -> Bool {
guard let first = first, let second = second else {
return false
}
if let equatableOne = first as? any Equatable, let equatableTwo = second as? any Equatable {
return equatableOne.isEqual(equatableTwo)
}
if first as AnyObject === second as AnyObject {
return true
}
guard let first = first as? [AnyHashable: Any], let second = second as? [AnyHashable: Any] else {
return false
}
guard first.count == second.count else {
return false
}
for (key, value) in first {
guard areEqual(first: value, second: second[key]) else {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment