Swift 上的常见可等式 class

Common Equatable class on Swift

我需要 Any Equatable 项目的容器 NOT Generic class(对于示例 UI classes initial from storyboard)。我需要这样

var items: [Equatable]?

但它不起作用,Equatable 需要 Generic。不存在的问题 common Equatable class.


好的 - 转到通用!但是如果我这样做

class Item<Value: Equatable>: Equatable {
   var value: Value
   init(_ value: Value) {
       self.value = value
   }
   //Equatable
   public static func ==(lhs: Item, rhs: Item) -> Bool {
       return (lhs.value == rhs.value)
   }
}

然后我将被迫在我的nonGeneric-UI class中指定类型。像这样

var items: [Item<WhatShouldBeHere?>]?

但我们又遇到了不存在共同点的问题 Equatable class


All Equatable 容器的任何解决方案?

代替存在类型,您需要使用类型橡皮擦:

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

    public init<E: Equatable>(_ value: E) {
        self.value = value
        self.equals = { ([=10=] as? E) == value }
    }

    public static func == (lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
        return lhs.equals(rhs.value) || rhs.equals(lhs.value)
    }
}

用法示例:

let items = [
    AnyEquatable(1),
    AnyEquatable(1.23),
    AnyEquatable(true),
    AnyEquatable("some string")
]

let desired = "some string"
let desiredAsAnyEquatable = AnyEquatable(desired)
let desiredDescription = String(reflecting: desired)

for item in items {
    let itemDescription = String(reflecting: item.value)
    let isEqualToDesired = item == desiredAsAnyEquatable
    print("\(itemDescription) is \(isEqualToDesired ? "": "not ")equal to \(desiredDescription)")
}

示例输出:

1 is not equal to "some string"

1.23 is not equal to "some string"

true is not equal to "some string"

"some string" is equal to "some string"