Nawin Phunsawat
Nawin Phunsawat

Reputation: 85

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.

Upvotes: 2

Views: 161

Answers (2)

Mahendra
Mahendra

Reputation: 8904

You can do the following:

do {
    let myStruct = try JSONDecoder().decode(GeneralResponse<Model>.self, from: jsonData)
    print(myStruct.dataResponse.name)
    print(myStruct.dataResponse.lname)
} catch {
    print("error: \(error)")
}

Upvotes: 0

Hitesh Surani
Hitesh Surani

Reputation: 13537

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)
})

Upvotes: 1

Related Questions