简体   繁体   中英

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

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. Most likely because testing a==b in the default case, calls the function itself again. 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?

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:

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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