3

I need to compare arrays of structs that conform to a protocol P.

P can't conform to Equatable because it must not have "Self requirements".

Creating AnyEquatable as a type erasure is a common practice for this purpose. However, AnyHashable is already part of the standard library and it conforms to Equatable.

I wonder if AnyEquatable is not part of the standard library for a good reason. Should the standard AnyHashable be used instead of AnyEquatable?

0

1 Answer 1

1

AnyHashable wraps up a bunch of common functionality. That AnyEquatable doesn't; what it does can be represented with just a closure.

let cupcake = "🧁"
let notCake = 0xca_e

let cupcakeEquals: (Any) -> Bool = try cupcake.getEquals()
XCTAssert( cupcakeEquals(cupcake) )
XCTAssertFalse( cupcakeEquals(notCake) )

let notCakeEquals = try notCake.getEquals(Any.self)
XCTAssert( notCakeEquals(notCake) )
XCTAssertFalse( notCakeEquals(cupcake) )

XCTAssertThrowsError( try cupcake.getEquals(Int.self) )
public extension Equatable {
  /// A closure that equates another instance to this intance.
  /// - Parameters:
  ///   - _: Use the metatype for `Castable` to avoid explicit typing.
  /// - Throws: `CastError.impossible` if a `Castable` can't be cast to `Self`.
  func getEquals<Castable>(_: Castable.Type = Castable.self) throws -> (Castable) -> Bool {
    if let error = CastError(self, desired: Castable.self)
    { throw error }

    return { self == $0 as? Self }
  }
}
/// An error that represents casting gone wrong. 🧙‍♀️🙀
public enum CastError: Error {
  /// An undesired cast is possible.
  case possible

  /// An desired cast is not possible.
  case impossible
}

public extension CastError {
  /// `nil` if  an `Instance` can be cast to `Desired`. Otherwise, `.impossible`.
  init?<Instance, Desired>(_: Instance, desired _: Desired.Type) {
    self.init(Instance.self, desired: Desired.self)
  }

  /// `nil` if  a `Source` can be cast to `Desired`. Otherwise, `.impossible`.
  init?<Source, Desired>(_: Source.Type, desired _: Desired.Type) {
    if Source.self is Desired.Type
    { return nil }

    self = .impossible
  }

  /// `nil` if  an `Instance` cannot be cast to `Undesired`. Otherwise, `.possible`.
  init?<Instance, Undesired>(_: Instance, undesired _: Undesired.Type) {
    self.init(Instance.self, undesired: Undesired.self)
  }

  /// `nil` if  a `Source` cannot be cast to `Undesired`. Otherwise, `.possible`.
  init?<Source, Undesired>(_: Source.Type, undesired _: Undesired.Type) {
    guard Source.self is Undesired.Type
    else { return nil }

    self = .possible
  }
}

You could wrap that, to conform to Equatable, with Cast being Any. Is there a use case?

/// A type-erased equatable value.
///
/// An `Equatable` instance is stored as a "`Cast`".
/// Only instances that can be cast to that type can be `==`'d with the `AnyEquatable`.
public struct AnyEquatable<Cast> {
  public init<Equatable: Swift.Equatable>(_ equatable: Equatable) throws {
    equals = try equatable.getEquals()
    cast = equatable as! Cast
  }

  private let equals: (Cast) -> Bool
  private let cast: Cast
}

extension AnyEquatable: Equatable {
  public static func == (equatable0: Self, equatable1: Self) -> Bool {
    equatable0 == equatable1.cast
  }
}

public extension AnyEquatable {
  static func == (equatable: Self, castable: Cast) -> Bool {
    equatable.equals(castable)
  }

  static func == (castable: Cast, equatable: Self) -> Bool {
    equatable.equals(castable)
  }
}
let anyEquatable = try AnyEquatable<Any>(cupcake)
XCTAssertEqual( anyEquatable, try .init(cupcake) )
XCTAssert(anyEquatable == cupcake)
XCTAssertFalse(notCake == anyEquatable)
3
  • Thanks, but this doesn’t explain why not to use AnyHashable over a custom type erasure (possibly more specific) like AnyEquatable (or another flavor like your suggestion). Would you consider your suggestion simpler/better/easier than using AnyHashable? And still, why AnyEquatable is not part of the standard library?
    – Yoav
    Commented Apr 23, 2020 at 6:06
  • I'm saying there's no use case; getEquals is probably more than needed. But show the use case if you have one! AnyHashable is what you use to erase Hashable things, because there are properties and methods associated with them. I'm saying it's not worth it to have a type, for what boils down to an operator. I think you're just looking at AnyHashable because it exists already, not because it wraps up almost as little as you actually want.
    – user652038
    Commented Apr 23, 2020 at 6:31
  • 1
    AnyHashable is also optimized by the compiler. It's slightly magical to avoid having to wrap it in a box. It primarily exists for NSDictionary to Dictionary bridging as far as I know. If you're finding you need AnyEquatable a lot or AnyHashable unrelated to bridging to Cocoa, you're probably misusing the type system IMO. Generally you should not make protocols require Equatable; you should add a custom .isEqual requirement if necessary. I discuss this around 37:44 here: youtube.com/watch?v=DXwJg0QTlZE
    – Rob Napier
    Commented Apr 23, 2020 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.