我需要比较符合协议P
的结构数组。
[P
无法符合Equatable,因为它必须没有“自我要求”。
创建AnyEquatable
作为类型擦除是为此目的的常见做法。但是,AnyEquatable
已经是标准库的一部分,并且符合AnyHashable
。
我想知道Equatable
是否不属于标准库是有充分的理由的。应该使用标准的AnyEquatable
代替AnyHashable
吗?
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 }
}
}