Search code examples
iosswiftcombine

Cannot convert return expression of return type 'AnyPublisher<T, ServiceError>'


I am new to combine . I have the generic function by using combine and return the Result which is T and Error (service error ). I am trying to pass the custom error message if the URL request is failed . It giving me following errors ..

Cannot convert return expression of type 'ServiceError' to return type 'AnyPublisher<T, ServiceError>'

Here is my URLRequest code ..

import Foundation

extension URLRequest {
    static func getRequest(client: ServiceClient) ->URLRequest? {
        guard var urlComponents = URLComponents(string:client.baseUrl + client.path) else {
            return nil
        }
        urlComponents.query = "\(client.params)"
        guard let url = urlComponents.url else {
            return nil
        }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = client.method
        return urlRequest
    }
}

Here is the network layer code ..

class ServiceImpl: Service {

    let urlSesson = URLSession(configuration: .default)
    var dataTask:URLSessionDataTask?

    func fetchData<T:Codable>(client: ServiceClient, type:T.Type) -> AnyPublisher<T,ServiceError> {

        dataTask?.cancel()

        guard let request = URLRequest.getRequest(client: client) else {
            return ServiceError.requestNotCreated(message: Constants.requestNotCreated)**// error is here** 
        }
    }

Here is the screenshot ..

error


Solution

  • The method is declared to return a Publisher, so you need to return a publisher that represents an error. There is just a publisher for exactly that purpose - Fail:

    return Fail(outputType: type, failure: 
        ServiceError.requestNotCreated(message: Constants.requestNotCreated
    ).eraseToAnyPublisher()