Compare enums with associated values in Swift

前端 未结 2 1938
忘掉有多难
忘掉有多难 2020-12-21 02:29

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{
              


        
相关标签:
2条回答
  • 2020-12-21 02:49

    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)

    0 讨论(0)
  • 2020-12-21 03:06

    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.

    0 讨论(0)
提交回复
热议问题