Shehbaz Khan
Shehbaz Khan

Reputation: 2000

Generic parameter 'T' could not be inferred while calling a method

I am getting below error Generic parameter 'T' could not be inferred

I have created a method and when I am trying to call that method then getting that error. I am adding both methods below.

 func requestNew<T> ( _ request: URLRequest, completion: @escaping( Result< T ,  NetworkError>) -> Void ) where T : Decodable {

         URLCache.shared.removeAllCachedResponses()

    print("URL \((request.url as AnyObject).absoluteString ?? "nil")")
        //use the currentrequest for cancel or resume alamofire request
        currentAlamofireRequest =   self.sessionManager.request(request).responseJSON { response in
             //validate(statusCode: 200..<300)
            if response.error != nil {
                var networkError : NetworkError = NetworkError()
                networkError.statusCode = response.response?.statusCode
                if response.response?.statusCode == nil{
                    let error = (response.error! as NSError)
                    networkError.statusCode = error.code
                }
                //Save check to get the internet connection is on or not
                if self.reachabilityManager?.isReachable == false {
                    networkError.statusCode = Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue)

                }

                completion(.failure(networkError))
            }else{
                print("response --- > ",String(data: response.data!, encoding: .utf8) ?? "No Data found")
                if let responseObject = try? JSONDecoder().decode(T.self, from: response.data!) {
                    completion(.success(responseObject.self))
                }else {
                }

            }
        }
    }

Below is screenshot of error ![ ]1

func getVersion1(complete :@escaping (Response<Version>) -> Void, failure:@escaping onFailure) {
self.network.requestNew(self.httpRequest) { (result) in
    print("hello")
}

Upvotes: 0

Views: 323

Answers (1)

OOPer
OOPer

Reputation: 47896

When Swift cannot infer the generic parameter, although it accepts the generic declaration of the method, you can specify the type by passing type fixed parameters.

Try this:

    func getVersion1(complete :@escaping (Response<Version>) -> Void, failure:@escaping onFailure) {
        self.network.requestNew(self.httpRequest) { (result: Result<Version, NetworkError>) in
            print("hello")
        }
    }

You may need to change Result<Version, NetworkError> to Result<SomeDecodableType, NetworkError>, if Version is not the type you expect from the request.

Upvotes: 2

Related Questions