Common Errors while coding in Swift

Nishant Paul
2 min readJan 29, 2021

--

Error 1: Generic parameter ‘T’ could not be inferred

While writing a generic function in Swift with a completion handler that returns a data of generic type <T>, I encountered an error while calling the generic function from my view model class.

Generic parameter ‘T’ could not be inferred

Generic function:

func fetchList<T: Decodable>(completionHandler: @escaping CompletionHandler<T>)

Calling function:

func callApi() {    ...    webService.fetchList { (result) in        switch result {        case .success(let data):            print( data)        case .failure(let error):           print(error)    }}

The generic function could not infer the type of <T> from the calling function. Fair enough, as my calling function does not provide the type <T> because the generic function (the function being called) did not have a parameter (or any other way) to specify type <T>. This baffled me for some time. Though I knew that somehow I have to provide type <T>, I was not sure how.

For example, it would be easy to provide type <T> if the generic function had a parameter that accepts type <T> reference as an argument.

Let’s see here:

func fetchList<T: Decodable>(val: T, completionHandler: @escaping CompletionHandler<T>)

However, our generic function does not look as easy as the above-mentioned one.

Going through some GitHub issues, I found the following solution of providing the generic type <T> without passing in the parameter value of the function. In the calling function, we just need to specify explicitly the type of result that we are expecting from the generic function. Therefore, we can specify <T> in the following way as well.

func callApi() {    ...    webService.fetchList { (result: Result<[ResponseModel], AppError>) in        switch result {        case .success(let data):        print( data)        case .failure(let error):
print(error)
}}

Voila! the issue is gone now as the generic function can infer the type of <T>.

--

--

Nishant Paul

iOS Application Developer / Technology Enthusiast @Dream11