29

I need to get a generic variable for a struct for parsing a JSON

but there is an error that I am getting Type 'BaseJsonModel' does not conform to protocol 'Codable

Below is my struct

  struct BaseJsonStruct<T>: Codable {
    let info: String
    let data: T
 }

Error:- Type 'BaseJsonModel' does not conform to protocol 'Codable'

Ekra
  • 3,241
  • 10
  • 41
  • 61

1 Answers1

58

T must also conform to Codable

struct BaseJsonStruct<T : Codable> : Codable {
    let info: String
    let data: T
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • If I used let item = try? decoder.decode(BaseJsonStruct.self, from: data). than I get error - Generic parameter 'T' could not be inferred – Ekra Mar 28 '18 at 09:56
  • do you have any idea of the same – Ekra Mar 28 '18 at 09:57
  • You have to specify the static type for example `decoder.decode(BaseJsonStruct.self, from: data` – vadian Mar 28 '18 at 09:58
  • tried but the value in variable comes as nil let itm1 = try? decoder.decode(BaseJsonStruct.self, from: data). But it compiles now alteast – Ekra Mar 28 '18 at 10:14
  • 2
    No, at the moment you use a generic you **must** specify the static type. `BaseJsonStruct` is not possible, it must be `BaseJsonStruct` or `BaseJsonStruct` or something else which conforms to `Codable`. `Codable` relies on concrete types. The decoder cannot decode dynamic types. – vadian Mar 28 '18 at 10:17
  • @vadian great answer but in my case it is BaseJsonStruct and I got stuck with it for quite so long. Give me your hands please to solve this issue. – EK Chhuon Jul 03 '19 at 02:37