Search code examples
swiftswift4alamofirerx-swiftswift4.2

Cannot put error with Generic Result enum in RxSwift


I'm trying to create a generic results enum in swift, this is what I have so far:

enum Result<T: Codable>: Error {
    //Indicates that it was a success, and data is the returned result
    case Success(data: T)

    //Indicates that there was an unrecognizable error
    case Failure(error: Error)

    //Some cases for specific status codes
    case Forbidden              //Status code: 403
    case NotAcceptable          //Status code: 406
    case Conflict               //Status code: 409
    case InternalServerError    //Status code: 500
}

And then I try to create an Observable out of it, like this: (The T is specified in the function's call, this is shortened for brevity)

Observable<Result<T>>.create { observer in 
    //Some code to go make an Http requests and return response....
    switch response.result {
        case .success(let value):
            //This works fine
            observer.onNext(Result.success(value))
            observer.onCompleted()
        case .failure(let error):
            //This is where things go wrong.
            observer.onError(Result.failure(error))
    }
}

The problem is when I try to return in the .failure case, it always says Argument type 'Result<_>' does not conform to expected type 'Error' even though Result is an Error type

Am I doing something wrong?


Solution

  • Other than the fact that your capitalization is all over the place... When you do Result.failure(anError) the compiler can't infer the type of T. To fix just do: Result<T>.failure(anError)

    ... Or should it be Result<T>.Failure(error: anError)? You have it capitalized and use a named variable in the definition but you use lower-case and don't use a named variable where it's being used. :-(