Last active
February 20, 2024 13:28
-
-
Save ollieatkinson/9fa246abf21a09a52d7c7c6e6149dc1e to your computer and use it in GitHub Desktop.
Equatable `Any` using existential
This file contains 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
public func isEqual(_ x: Any, _ y: Any) -> Bool { | |
if let isEqual = (x as? any Equatable)?.isEqual(to: y) { | |
return isEqual | |
} else if let equatable = x as? AnyEquatable { | |
return equatable.isEqual(to: y) | |
} else { | |
return (x as? any OptionalProtocol).isNil && (y as? any OptionalProtocol).isNil | |
} | |
} | |
private func __isEqual(_ x: Any, _ y: Any) -> Bool { | |
isEqual(x, y) | |
} | |
extension Equatable { | |
fileprivate func isEqual(to other: Any) -> Bool { | |
self == other as? Self | |
} | |
} | |
protocol AnyEquatable { | |
func isEqual(to other: Any) -> Bool | |
} | |
extension Dictionary: AnyEquatable { | |
func isEqual(to other: Any) -> Bool { | |
guard let other = other as? [Key: Any] else { return false } | |
return allSatisfy { k, v in | |
other[k].map { __isEqual($0, v) } ?? false | |
} | |
} | |
} | |
extension Array: AnyEquatable { | |
func isEqual(to other: Any) -> Bool { | |
guard let other = other as? [Any] else { return false } | |
return Swift.zip(self, other).allSatisfy(__isEqual) | |
} | |
} |
Author
ollieatkinson
commented
Feb 20, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment