Skip to content

Instantly share code, notes, and snippets.

@philosopherdog
Forked from JadenGeller/AnyEquatable.swift
Created October 13, 2021 13:58
Show Gist options
  • Save philosopherdog/ea7f721946ba790a02340d2458cc6b46 to your computer and use it in GitHub Desktop.
Save philosopherdog/ea7f721946ba790a02340d2458cc6b46 to your computer and use it in GitHub Desktop.
AnyEquatable
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)
}
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