Leandro P
Leandro P

Reputation: 213

Is it possible to use a generic inside a generic struct init in Swift?

I would like to know if it is possible to use a generic type to initialize another generic. I put a example code below.

struct Object: Decodable {
    let id: String?
    let type: String?
}

struct JSON<T: Decodable>: Decodable {
    let data: T?
}

func test<T: Decodable>(type: T.Type) {
    let dataFromAPI = Data()
    let model = JSONDecoder().decode(JSON<type>, from: dataFromAPI)
}

I am receiving this error message:

Use of undeclared type 'type'

Upvotes: 0

Views: 524

Answers (1)

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

If you want to call generic type struct then use this:

   do {
     let model = try JSONDecoder().decode(JSON<T>.self, from: dataFromAPI)

   } catch let message {
        print("JSON serialization error:" + "\(message)")
   }

Or if you want to decode simple struct then:

   do {
     let model = try JSONDecoder().decode(Object.self, from: dataFromAPI)

   } catch let message {
        print("JSON serialization error:" + "\(message)")
   }

Upvotes: 1

Related Questions