Overloading Equality Operators in Fast Enumerations with Related Values

I know that almost the same question was asked before, but I can not comment on it, because I'm here for a new one. That is why I am posting a separate question. Also my question is a continuation of the previous question asked and aims at a more general solution. This is a link to a previous question: How to check equality of Swift enumerations with related values

I want to check equality in an enumeration with related 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 configure the overload function as follows

 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 does not give a compile-time error, but does not work with bad_exec in a running process. Most likely because testing a == b in the default case calls this function again. The .Function part works as expected, but not everything else ... So, the list of cases is somewhat longer, how can I check cases that do not have an associated value for equality?

+5
source share
2 answers

In your implementation

 if (a == b) { 

recursively calls the same == function. This causes a stack overflow failure.

For example, a working implementation:

 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 } } 
+2
source

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 do not recommend this :)

0
source

Source: https://habr.com/ru/post/1214974/


All Articles