0

I create a enum type (Swift 4.0):

enum TraceResult{
    case nothing
    case success
    case failed
    case custom(String)   //#1
}

after that I decide to compare two enum values :

let tr = TraceResult.nothing
if tr == TraceResult.success{    //#2
    //do something...
}

and compiler will complain a error in line #2:

Binary operator '==' cannot be applied to two 'TraceResult' operands

If I remove line #1,It's all right!!!

Or I used 'switch' statement to compare them ,It's also OK!!!

So Is possible to compare two TraceResult values with 'if' statement???

Thanks ;)

1
  • if I feel below 2 answers is all right,what should I do???How to select the "right answer"??? Thanks! Commented Jun 15, 2018 at 2:43

2 Answers 2

4

if case can be used to compare enum values.

You use

if case .success = tr {
    // do something
}

Instead of the == comparison you are doing currently.

Sign up to request clarification or add additional context in comments.

1 Comment

@hopy please mark this answer as correct cause it's the easier way.
3

You need to declare a conformance to Equatable for your type:

enum TraceResult: Equatable {
    case nothing
    case success
    case failed
    case custom(String)
}

As of Swift 4.1, the compiler will automatically synthesize the definition of the == function for you. Prior to 4.1, you would need to manually implement, like so:

extension TraceResult: Equatable {
    static func == (lhs: TraceResult, rhs: TraceResult) -> Bool {
        switch (lhs, rhs) {
            case (.nothing, .nothing): return true
            case (.success, .success): return true
            case (.failed, .failed): return true
            case (.custom(let s1), .custom(let s2)) where s1 == s2: return true

            case _: return false
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.