比较忽略关联值的Swift Enum类型 - 通用实现

Ana*_*sia 5 enums swift swift-protocols

我的项目中有几个不同的枚举,符合相同的协议.compareEnumType协议中的方法比较忽略关联值的枚举案例.这是我在游乐场的代码:

protocol EquatableEnumType {
    static func compareEnumType(lhs: Self, rhs: Self) -> Bool
}

enum MyEnum: EquatableEnumType {
    case A(Int)
    case B

    static func compareEnumType(lhs: MyEnum, rhs: MyEnum) -> Bool {
        switch (lhs, rhs) {
        case (.A, .A): return true
        case (.B, .B): return true
        default: return false
        }
    }
}

enum MyEnum2: EquatableEnumType {
    case X(String)
    case Y

    static func compareEnumType(lhs: MyEnum2, rhs: MyEnum2) -> Bool {
        switch (lhs, rhs) {
        case (.X, .X): return true
        case (.Y, .Y): return true
        default: return false
        }
    }
}

let a = MyEnum.A(5)
let a1 = MyEnum.A(3)
if MyEnum.compareEnumType(lhs: a, rhs: a1) {
    print("equal") // -> true, prints "equal"
}

let x = MyEnum2.X("table")
let x1 = MyEnum2.X("chair")
if MyEnum2.compareEnumType(lhs: x, rhs: x1) {
    print("equal2") // -> true, prints "equal2"
}
Run Code Online (Sandbox Code Playgroud)

在我的真实项目中,我有超过2个枚举,并且对于每个枚举,我必须具有类似的compareEnumType功能实现.

问题是:是否可以使用compareEnumType符合EquatableEnumType协议的所有枚举的通用实现?

我尝试在协议扩展中编写一个默认实现,如下所示:

extension EquatableEnumType {
    static func compareEnumType(lhs: Self, rhs: Self) -> Bool {
        // how to implement???
    }
}
Run Code Online (Sandbox Code Playgroud)

但我坚持实施.我没有看到访问lhs和中包含的值的方法rhs.谁能帮助我?

Yan*_*ick 0

我不认为你可以自动生成它,所以这是一种使用扩展的方法。我建议创建一个新的enum CompareEnumMethod,告诉您是否要比较关联的values或仅比较type. compareEnum在协议中创建一个将此枚举作为参数的新函数。然后,您可以创建一个扩展,==(lhs:,rhs:)并说它使用.value,并且compareEnumType您使用.typecompareEnum现在只需在每个枚举中实现该方法。

enum CompareEnumMethod {
    case type, value
}

protocol EquatableEnumType: Equatable {
    static func compareEnumType(lhs: Self, rhs: Self) -> Bool
    static func compareEnum(lhs: Self, rhs: Self, method: CompareEnumMethod) -> Bool
}

extension EquatableEnumType {
    static func compareEnumType(lhs: Self, rhs: Self) -> Bool {
        return Self.compareEnum(lhs: lhs, rhs: rhs, method: .type)
    }

    static func ==(lhs: Self, rhs: Self) -> Bool {
        return Self.compareEnum(lhs: lhs, rhs: rhs, method: .value)
    }
}

enum MyEnum: EquatableEnumType {
    case A(Int)
    case B

    static func compareEnum(lhs: MyEnum, rhs: MyEnum, method: CompareEnumMethod) -> Bool {
        switch (lhs, rhs, method) {
        case let (.A(lhsA), .A(rhsA), .value):
            return lhsA == rhsA
        case (.A, .A, .type),
             (.B, .B, _):
            return true
        default:
            return false
        }
    }
}

let a0 = MyEnum.A(5)
let a1 = MyEnum.A(3)
let b0 = MyEnum.B
print(MyEnum.compareEnumType(lhs: a0, rhs: a1)) //true
print(a0 == a1) //false
print(MyEnum.compareEnumType(lhs: a0, rhs: b0)) //false
Run Code Online (Sandbox Code Playgroud)