Last active
January 6, 2024 18:26
-
-
Save JadenGeller/f0d05a4699ddd477a2c1 to your computer and use it in GitHub Desktop.
AnyEquatable
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 struct AnyEquatable: Equatable { | |
private let value: Any | |
private let equals: Any -> Bool | |
public init<E: Equatable>(_ value: E) { | |
self.value = value | |
self.equals = { ($0 as? E == value) ?? false } | |
} | |
} | |
public func ==(lhs: AnyEquatable, rhs: AnyEquatable) -> Bool { | |
return lhs.equals(rhs.value) | |
} |
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
let w = AnyEquatable(5) | |
let x = AnyEquatable(5) | |
let y = AnyEquatable(6) | |
let z = AnyEquatable("Hello") | |
print(w == x, w == y, w == z) // -> true false false | |
let arr = [AnyEquatable(55), AnyEquatable("dog")] // cool | |
print(arr.contains(AnyEquatable("dog")), arr.contains(AnyEquatable(10))) // -> true false | |
// Note that two values are only equal if they are the same type | |
print(AnyEquatable(5 as Int) == AnyEquatable(5 as Double)) // -> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to fix a couple of compilation issues under Swift 4.2: