AnyHashable替代AnyEquatable

问题描述 投票:2回答:1

我需要比较符合协议P的结构数组。

[P无法符合Equatable,因为它必须没有“自我要求”。

创建AnyEquatable作为类型擦除是为此目的的常见做法。但是,AnyEquatable已经是标准库的一部分,并且符合AnyHashable

我想知道Equatable是否不属于标准库是有充分的理由的。应该使用标准的AnyEquatable代替AnyHashable吗?

swift type-erasure
1个回答
0
投票

AnyEquatable包装了许多常用功能。那AnyHashable不是;它所做的只是一个闭包即可。

AnyEquatable
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() as (Int) -> Bool
)
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? = nil) throws -> (Castable) -> Bool {
    if let error = CastError.Impossible(self, Castable.self)
    { throw error }

    return { self == $0 as? Self }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.