How to compare Equatables

Hi there,

I have a question. How can I compare Any objects when they are actually Equatable? If it happens to be Hashable, I can use AnyHashable just like the sample below, but there's not such thing as AnyEquatable. What's the recommended way?

struct Person {
  let age: Int
  let name: String
}

func test<T: Equatable>(_ p1: Person, _ p2: Person, _ k: KeyPath<Person, T>) -> Bool {
  return p1[keyPath: k] == p2[keyPath: k]
}

func test(_ p1: Person, _ p2: Person, _ arr: [PartialKeyPath<Person>]) -> Bool {
  for k in arr {
    if let h1 = p1[keyPath: k] as? AnyHashable, let h2 = p2[keyPath: k] as? AnyHashable {
      if h1 != h2 { return false }
    } else {
      // how am I supposed to compare them?
    }
  }
  return true
}

let bob = Person(age: 42, name: "bob")
let jon = Person(age: 42, name: "jon")

test(bob, jon, \.age)  // true
test(bob, jon, [\Person.age, \Person.name])  // can't omit Person but besides the point

Should I implement AnyEquatable just like AnyHashable? I'm not familiar with the magic behind downcasting but can I implement so that I should be able to make "foo as? AnyEquatable" work?

The easiest thing to do would be to require Hashable and use AnyHashable. It is not possible to extend downcasting to implement your own AnyEquatable type.

Darnit. I have a type which is Equatable but not Hashable was the reason I posted my question.

So, why don't we have AnyEquatable? Is it not possible to implement even in stdlib? Don't we want it?

Terms of Service

Privacy Policy

Cookie Policy