rodalfus rodalfus - 1 month ago 4
iOS Question

Handling an Error with custom parameter in an if-statement in Swift

I created a custom enum conforming to

Error
in Swift as such:

enum CustomError: Error{
case errorWith(code: Int)
case irrelevantError
}


CustomError
can optionally be returned from an asynchronous function through a closure like so:

func possiblyReturnError(completion: (Error?) -> ()){
completion(CustomError.errorWith(code: 100))
}


I would now like to check the type of
CustomError
that is returned in the closure. Along with that, if it is a
CustomError.errorWith(let code)
, would like to extract the code of that
CustomError.errorWith(let code)
. All of this I would like to be done using the condition of an if-statement. Along the lines of this:

{ (errorOrNil) in
if let error = errorOrNil, error is CustomError, // check if it is an
//.errorWith(let code) and extract the code, if so
{
print(error)
}
else {
print("The error is not a custom error with a code")
}
}


Is this at all possible using Swift 3.0? I tried various combinations that I could think of, however, all attempts have been fruitless and ended in compilation time errors.

Answer

Do this

{ (errorOrNil) in
    if let error = errorOrNil as? CustomError, case let .errorWith(code) = error {
       print(code, error)
    } else {
       print("The error is not a custom error with a code")
    }
}

Or use switch instead of if.