Search code examples
swiftenumsalamofire

Swift enum evaluation


Using Alamofire we're trying to determine if an error is a certain kind of error (response code 499) as represented by a "nested" AFError enum:

    if response.result.isFailure {
        if let aferror = error as? AFError {
            //THIS LINE FAILS 
            if (aferror == AFError.responseValidationFailed(reason: AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 499))) {
               ....
            }
        }            
    }

But this results in the compiler error:

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

How can you do this?


Solution

  • Well, you could trying extending AFEError to conform to Equatable in order to use ==, but you are probably better off using switch and pattern matching:

    switch aferror {
        case .responseValidationFailed(let reason) :
            switch reason {
                case AFError.ResponseValidationFailureReason.unacceptableStatusCode(let code):
                    if code == 499 { print("do something here") }
                default:
                    print("You should handle all inner cases")
            {
        default:
            print("Handle other AFError cases")
    }
    

    This is the best syntax to ensure (and get the compiler to help you ensure) that all possible error cases and reasons are handled. If you only want to address a single case, like in your example, you can use the newer if case syntax, like this:

    if case .responseValidationFailed(let reason) = aferror, case AFError.ResponseValidationFailureReason.unacceptableStatusCode(let code) = reason, code == 499 {
        print("Your code for this case here")
    }