Search code examples
swiftalamofire

How to reference generic Alamofire DataResponse value


I would like to write a method that can accept any Alamofire DataResponse value. For example, I might pass in DataResponse<Any> or DataResponse<String>. I cannot find a way to get this to work however. For example if I try just using "DataResonse" like this

static func isTimeout(response: DataResponse) -> Bool {
    if let error = response.result.error {
        if error._code == NSURLErrorTimedOut {
            return true
        }
    }
    return false
}

I get a compile error:

Reference to generic type 'DataResponse' requires arguments in <...>
Insert <Any>.

However if I change the parameter type to be DataResponse<Any>, it will not work for when I have DataResponse<String>. The compile error I get when I try to pass DataResponse<String> into the function is:

Cannot convert value of type 'DataResponse<String>' to expected argument type 'DataResponse<Any>'

I also tried DataResponse<AnyObject> and got the same error as above and DataResponse<Value> and got this error:

Use of undeclared type 'Value'

Any ideas on how to do this so I don't have to duplicate functions just for the slightly different parameter type?


Solution

  • Your forget to infer the generic type. Try this:

    static func isTimeout<T>(response: DataResponse<T>) -> Bool {