Noor Ahmed Natali
Noor Ahmed Natali

Reputation: 523

How to pass a function parameter to the generic structure in swift

I am trying to pass a model/struct as a parameter in function and passing it to another struct/model with generic type here is my code

---> Function

func getAPICallModelDecodable<T:Codable> (url:String,model:T,
                                          success: @escaping (_ responseObject:T?)->Void,
                                          failure: @escaping (_ error:String) -> Void ,
                                          method:HTTPMethod = .get) {
    print(type(of: model))
    AF.request(url,method:method).responseDecodable(of: FetchAPI<T(Want to pass model parameter here)>.self) { respons in
        print(respons)
        switch respons.result {
        case .success(let data):
            if data.flag! {
                success(data.data)
            }
        case .failure(let error):
            failure(error.localizedDescription)
        }
    }
}

---> FetchAPI Struct

struct FetchAPI<T:Codable>:Codable {
    
    var flag: Bool?
    var statusCode: Int?
    var message: String?
    var data: T?
    
    enum CodingKeys: String, CodingKey {
        case flag = "Flag"
        case statusCode = "StatusCode"
        case message = "Message"
        case data = "Data"
    }
}    

Model parameter can be any codable structure

Upvotes: 0

Views: 1052

Answers (1)

Johannes
Johannes

Reputation: 586

Currently your function getAPICallModelDecodable is defined in such a way that you have to pass in a model of type T. But if I understand it correctly, you only want to pass in (define) the type T.

For this you have to change the function as follows:

func getAPICallModelDecodable<T:Codable> (url: String, type: T.Type,
                                          success: @escaping (_ responseObject:T?)->Void,
                                          failure: @escaping (_ error:String) -> Void ,
                                          method:HTTPMethod = .get) 

In the function body you can use T e.g. simply like this:

AF.request(url,method:method).responseDecodable(of: FetchAPI<T>.self)

The function call would then look like this:

getAPICallModelDecodable(url: ..., type: Model.self, ...)

Upvotes: 2

Related Questions