Search code examples
iosswiftxcodegenericsdecodable

It is impossible to access the nested value in decoadable of generic type of struct in swift?


I want to know if i decode a data from api to generic type of model class, can i access in a nested value of generic type. sorry for bad english.

GeneralResponse.swift - class for map data to object have data class which be a generic type

struct GeneralResponse<T: Decodable>: Decodable {
    var code: String
    var dataResponse : T
}

Model.swift - model class for map in dataResponse field.

struct Model: Decodable {
    var name: String
    var lname: String
}

APIManager.swift - map a data from api to object (send type of Model )

var myStruct = try! JSONDecoder().decode(GeneralResponse<T>.self, from: jsonData)

ViewController.swift - call a method in APIManager

APIManager.callRequest(url: "someURL", type: Model.self)

In this case, i want to access to "name" or "lname" but it can't.


Solution

  • Please refer below code

    APIManager.swift

    func callRequest<T:Decodable>(url: String,modelClass:T.Type,SuccessBlock:@escaping (T) -> Void){
        do {
            var myStruct = try JSONDecoder().decode(GeneralResponse<T>.self, from: Data())
            SuccessBlock(myStruct.dataResponse)
        } catch let error {
            print(error)
        }
    }
    

    ViewController.swift

    callRequest(url:"someURL",modelClass: Model.self, SuccessBlock: { (response) in
         print(response.lname,response.name)
    })