"Unable to infer type of a closure parameter 'b' in the current context". Getting this error while calling the function

getting error while calling the function.

func hitService<T : Codable>(urlS: String , completion : @escaping (T) -> Void) {
    
    guard let url = URL(string: urlS) else {return}
    
    
    let session = URLSession.shared
    
    let _ = session.dataTask(with: url) { dt, resp, err in
        
        
        let decoder = JSONDecoder()
        
        if let d = dt {
            
            do {
                let obj = try decoder.decode(T.self, from: d)
                completion(obj)
            } catch {print(error.localizedDescription)}
        }
    }.resume()
}

calling function like this and getting error on it.
I’ve tried passing a data type inside <> as well.

 hitService(urlS: urlStr) { b in
        
        
        
  }

>Solution :

The generic function relies on you specifying a type when it’s called so it can infer the types it uses.

In this case you’ll need to supply the type of the closure parameter b i.e.

hitService(urlS: urlStr) { (b: MyType) in
    
}

Leave a Reply