Search code examples
swiftgenericsalamofireobjectmapper

Swift function generic parameter


So, I am using alamofire and object mapper library from github.

In my function there is this code

Alamofire.request(urlRequest).responseObject { (response: DataResponse<News>) in }

I do the response checking together with the status code also

switch response.result {
            case .success:
                if let object = responseObject {
                    completion(object)
                }
                break;
            case .failure(let error):
                print(error)
                if let statusCode = response.response?.statusCode {
                    var message = String()
                    switch statusCode {
                        //status code checking here 
                    }
                }
                else {
                    var message = String()
                    message = error.localizedDescription
                }
                break;
        }

So i have several api calling and all of the api calling will also implement this status code checking. I don't want to keep copy pasting this chunk of code for all my api call function

So what i am planning to do is to create a dedicated function to check the status code from the api call

But i face one problem. How can I create a generic function parameter that accept all type of DataResponse<>?

I tried to run this code but failed

// validateResponse function
static func validateResponse(dataResponse: DataResponse<Any>) -> String {
    // status code checking here 
}

// inside the alamofire.request response
validateResponse(dataResponse: response)

// return me this error 
Cannot convert value of type 'DataResponse<News>' to expected argument type 'DataResponse<Any>'

The DataResponse<> will always change based on the model provided into the alamofire.responseObject

Can anyone guide me on how to do it properly? Thanks!


Solution

  • You need to use generics!

    static func validateResponse<T>(dataResponse: DataResponse<T>) -> String {
        // status code checking here 
    }
    

    Usage:

    validateResponse(dataResponse: response)
    

    The generic parameter T will be inferred be News it will be as if the method is like this:

    static func validateResponse(dataResponse: DataResponse<News>) -> String {
        // status code checking here 
    }