Victor Mendes
Victor Mendes

Reputation: 179

Swift 4 generics with struct

I'm trying to use generics with Codable protocol, but I'm getting an error.

Cannot invoke 'decode' with an argument list of type '([T.Type], from: Data)

static func getRequest<T>(model: T.Type, url: String, parameters: [String: Any]? = nil, headers: [String: String]? = nil, data: @escaping (Any?, Any?, Error?) -> ()) -> Alamofire.DataRequest {

     return Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: headers)
        .validate(contentType: [RequestHelper.HeaderKeys.contentTypeJson])
        .responseJSON { (response) in
            print(response)
            switch response.result {
            case .success:
                let responseData = response.data!
                do {
                    print(model)
                    print(T.self)
                    let decodable = try JSONDecoder().decode([model].self, from: responseData)
                    data(response.response?.allHeaderFields, decodable, nil)
                } catch let error {
                    data(nil, nil, error)
                }
            case .failure(let requestError):
                data(nil, nil, requestError)
                print(requestError)
            }
    }
}

I need pass my struct model to this method

How can I fix this? Does anyone could help me?

Upvotes: 1

Views: 469

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17050

decode() can only take a type that is Decodable. You need to specify that in your method signature. Either add where T: Decodable at the end of getRequest's declaration or just put <T: Decodable> inside the brackets to restrict T to decodable types only, and then you should be able to pass your parameter to decode().

EDIT: Looking at your code, there's another error:

let decodable = try JSONDecoder().decode([model].self, from: responseData)

Instead of [model].self, you need to pass [T].self. Otherwise you're passing an array of types rather than the type of an array.

Upvotes: 2

Related Questions