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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With