简体   繁体   English

具有相关值的swift枚举中的等于运算符重载

[英]equality operator overloading in swift enums with associated values

I know an almost similar question was asked earlier, but I am not able to comment on it, because I am to new here. 我知道之前有一个几乎相似的问题,但是我无法对此发表评论,因为我是新来的。 That is the reason why I am posting a separat question. 这就是我发布分离问题的原因。 Also my question is an extension to the previous question asked and is aimed at a more general solution. 此外,我的问题是对上一个问题的扩展,旨在提供更一般的解决方案。 That is the link to the previous question: How to test equality of Swift enums with associated values 这是前一个问题的链接: 如何测试Swift枚举与相关值的相等性

I want to test equality in an enum with associated values: 我想在枚举中测试相关值的相等性:

enum MyEnum {
    case None
    case Error
    case Function(Int) // it is a custom type but for briefness an Int here
    case ...
}

I tried to setup an overloading function as the following 我试着设置一个重载函数,如下所示

func ==(a: MyEnum, b: MyEnum) -> Bool {
    switch (a,b) {
    case (.Function(let aa), .Function(let bb)):
        if (aa==bb) {
            return true
        } else {
            return false
        }
    default:
        if (a == b) {
            return true
        } else {
            return false
        }
    }
}

This gives no compile time error, but fails with bad_exec in the running process. 这不会产生编译时错误,但在运行过程中会因bad_exec而失败。 Most likely because testing a==b in the default case, calls the function itself again. 很可能是因为在默认情况下测试a == b,再次调用函数本身。 The .Function part works as expected, but not the rest... So the case list is somewhat longer, how can I test the cases which do not have an associated value with them for equality? .Function部分按预期工作,但不是其余的...所以案例列表有点长,我如何测试与它们没有相关值的案例是否相等?

In your implementation, 在您的实施中,

if (a == b) {

recursively calls the same == function again. 递归地再次调用相同的==函数。 This eventually crashes with a stack overflow. 这最终会因堆栈溢出而崩溃。

A working implementation would for example be: 例如,一个有效的实施方案是:

func ==(a: MyEnum, b: MyEnum) -> Bool {
    switch (a,b) {
    case (.Function(let aa), .Function(let bb)):
        return aa == bb
    case (.Error, .Error):
        return true
    case (.None, .None):
        return true
    default:
        return false
    }
}

Although memcmp works: 虽然memcmp有效:

func ==(var a: MyEnum, var b: MyEnum) -> Bool {
    switch (a,b) {
    case (.Function(let aa), .Function(let bb)):
        return aa == bb
    default:
        return memcmp(&a, &b, sizeof(MyEnum)) == 0
    }
}

I don't recommend this :) 我不推荐这个:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM