Bhavesh Dhaduk
Bhavesh Dhaduk

Reputation: 1906

Swift 4 Codable : Common struct for all model

Here i am getting API response of all of my api.

{
  "success" : true,
  "message" : "",
  "data" : {
        /multipal data parameter/ 
   }
}

And here is my codable model

struct Login: Codable {
    let success: Bool
    let message: String
    let data: Data

    struct Data: Codable  {

    }
}

How can i create common Sturct for success and message parameter.

Upvotes: 3

Views: 858

Answers (2)

kalpesh
kalpesh

Reputation: 1287

Common structure :

My common struture of model

I have created something like that

struct statusModel<T:Codable>: Codable {

    let message : String
    let resultData : [T]?
    let status : Int

    enum CodingKeys: String, CodingKey {
        case message = "message"
        case resultData = "resultData"
        case status = "status"
    }
}

Regular model (resultData)

struct modelInitialize : Codable {

    let profileimgurl : String?
    let projecturl : String?

    enum CodingKeys: String, CodingKey {
        case profileimgurl = "profileimgurl"
        case projecturl = "projecturl"
    }
}

You can set like as below

    do {
        guard let reponseData = responseData.value else {return} //Your webservice response in Data
        guard let finalModel = try?JSONDecoder().decode(statusModel<modelInitialize>.self, from: reponseData) else {return}
       }

Upvotes: 0

David Pasztor
David Pasztor

Reputation: 54716

You can make the root struct representing the network response generic, this will allow you to keep the success and message parts common between all specialised responses.

struct NetworkResponse<ResponseData:Codable>: Codable {
    let success: Bool
    let message: String
    let data: ResponseData
}

You shouldn't create custom types with the same name as built in types, since that will lead to confusion, especially for other people reading your code, so I renamed your custom Data type to ResponseData.

For instance you can create a LoginResponse model and decode it like below. You can do the same for other responses from the same API.

let loginResponse = """
{
    "success" : true,
    "message" : "",
    "data" : {
        "username":"test",
        "token":"whatever"
    }
}
"""

struct LoginResponse: Codable {
    let username: String
    let token: String
}

do {
    print(try JSONDecoder().decode(NetworkResponse<LoginResponse>.self, from: Data(loginResponse.utf8)))
} catch {
    print(error)
}

Upvotes: 4

Related Questions