0

Assuming I have two API calls

// /someurl/api/product-list
{
   "status":0,
   "message": "ok",
   "data":{
      "items":[
         {
            "id":1,
            "name":"iPhone",
            "desc":{
               "en-us":"This is an iPhone",
               "fr":"Ceci est un iPhone"
            }
         }
      ]
   }
}
// /someurl/api/movie-list
{
   "status":0,
   "message": "ok",
   "data":{
      "items":[
         {
            "imdb_id":"tt0081505",
            "title":"The Shining",
            "short_desc":{
               "en-us":"This is The Shining",
               "fr":"C'est le Shining"
            }
         }
      ]
   }
}

Now, both two api responses include the same structure of status, message(potentially would have pagination info object), except the data are different.

And In productModel

struct ProcuctAPIResponse: Codable {
    let status: Int
    let data: ProcuctAPIResponseData
    let message: String?
}

struct ProcuctAPIResponseData: Codable {
    let items: [Product]
}

struct Product: Codable {
    let id: Int
    let name: String?
    let desc: [String: String]?
}

And In movieModel

struct MovieAPIResponse: Codable {
    let status: Int
    let data: MovieAPIResponseData
    let message: String?
}

struct MovieAPIResponseData: Codable {
    let items: [Movie]
}

struct Movie: Codable {
    let imdb_id: Int
    let title: String?
    let short_desc: [String: String]?
}

My question is that is there a way I can create a BaseAPIResponse

something like

struct BaseAPIResponse: Codable {
    let status: Int
    let message: String?
}

then ProcuctAPIResponse and MovieAPIResponse can be extended from of it?

If not, how do you optimize these codes?

dummy
  • 21
  • 6
  • 1
    `Generic` might be the world you are looking for: https://stackoverflow.com/questions/49529208/ios-generic-type-for-codable-property-in-swift – Larme Dec 16 '21 at 10:20
  • yes!, that is exactly what I want! Thank you – dummy Dec 17 '21 at 02:27
  • https://stackoverflow.com/questions/50624158/can-we-reuse-struct-on-swift-or-is-there-any-other-way – dummy Dec 17 '21 at 02:28

1 Answers1

1

use protocols

protocol BaseAPIResponse: Codable {
  let status: Int
  let message: String?
}

Now implement the structs:

struct ProcuctAPIResponse: BaseAPIResponse {...}

movieModel

struct movieModel: BaseAPIResponse {...}
Mubashir Ali
  • 349
  • 1
  • 10
  • First of all you should fix your protocol declaration and remove spelling errors and making sure the syntax is correct. Secondly I don't see the advantage of a protocol here, you will still need to implement the two properties in each conforming type. – Joakim Danielson Dec 16 '21 at 10:55