Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active January 6, 2024 18:26
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JadenGeller/f0d05a4699ddd477a2c1 to your computer and use it in GitHub Desktop.
Save JadenGeller/f0d05a4699ddd477a2c1 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
@pepasflo
Copy link

pepasflo commented Oct 30, 2018

Updated to fix a couple of compilation issues under Swift 4.2:

import Foundation

public struct AnyEquatable {
    private let value: Any
    private let equals: (Any) -> Bool

    public init<T: Equatable>(_ value: T) {
        self.value = value
        self.equals = { ($0 as? T == value) }
    }
}

extension AnyEquatable: Equatable {
    static 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