Search code examples
swiftcodabledecodable

Decodable: Generic parameter 'T' could not be inferred


I've been staring at this for a while and I can't seem to figure out how to help the compiler. I'd like to make the functions generic so they can be reusable.

I removed everything inside the functions and where makeServiceCall gets called but I still see the error:

Generic parameter 'T' could not be inferred

public func sendURLRequest<T: Decodable>(url: URL, completion: @escaping (Result<T, Error>) -> Void) {

}

public func makeServiceCall<T: Decodable>(url: URL, _ completion: @escaping (T)-> Void ) {
    sendURLRequest(url: url){ response in
    }
}

If I add T to sendURLRequest sendURLRequest<T>(url: url) I see the warning:

Cannot explicitly specialize a generic function

. sendURLRequest<T: Decodable> returns another error:

Binary operator '<' cannot be applied to operands of type '(URL, @escaping (Result<_, Error>) -> Void) -> ()' and 'T.Type'

Thanks for any help! I'm on iOS 13


Solution

  • The compiler can't infer the type in this case, so you need to specify it explicitly:

    public func makeServiceCall<T: Decodable>(url: URL, _ completion: @escaping (T)-> Void ) {
        sendURLRequest(url: url) { (response: Result<T, Error>) in
        }
    }