Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare enums with associated values in Swift

For enums with associated values, Swift doesn't provide the equality operator. So I implemented one to be able to compare two enums:

enum ExampleEnum{
     case Case1
     case Case2(Int)
     case Case3(String)
     ...
}

func ==(lhs: ExampleEnum, rhs: ExampleEnum) -> Bool {

    switch(lhs, rhs){
    case (.Case1, .Case1): return true
    case let (.Case2(l), .Case2(r)): return l == r
    case let (.Case3(l), .Case3(r)): return l == r
    ...
    default: return false
    }
}

My problem is that I have a lot of such enums with a lot of cases so I need to write a lot of this comparison code (for every enum, for every case).

As you can see, this code always follows the same scheme, so there seems to be a more abstract way to implement the comparison behavior. Is there a way to solve this problem? For example with generics?

like image 977
tanaschita Avatar asked Feb 10 '23 08:02

tanaschita


2 Answers

As of Swift 4.2 just add Equatable protocol conformance. It will be implemented automatically.

enum ExampleEquatableEnum: Equatable {
    case case1
    case case2(Int)
    case case3(String)
}

print("ExampleEquatableEnum.case2(2) == ExampleEquatableEnum.case2(2) is \(ExampleEquatableEnum.case2(2) == ExampleEquatableEnum.case2(2))")
print("ExampleEquatableEnum.case2(1) == ExampleEquatableEnum.case2(2) is \(ExampleEquatableEnum.case2(1) == ExampleEquatableEnum.case2(2))")

I.e. default comparison takes associated values in account.

like image 72
Paul B Avatar answered Feb 11 '23 22:02

Paul B


Currently there is no way of achieving this without writing out all the cases, we can hope that it'll be possible in a later version.

If you really have a lot of cases and you don't want to write them all out, you can write a small function that generates the code automatically for you (I've been doing this just recently for something that wasn't possible to refactor)

like image 29
Kametrixom Avatar answered Feb 11 '23 22:02

Kametrixom