Renan Aguiar
Renan Aguiar

Reputation: 245

Generics on SWIFT Struct

Im trying to make generic structs on SWIFT to work with JSON and Codable, but i dont know if it is possible.

Without generics, it works.

struct apiContainer: Decodable {
    let meta: Meta
    let result: [Client]
}

I have a struct named "Client" and I would like to have other structs, for example: owner, plant and so on.

All JSON response has to go to apiContainer. It has Meta and [Client].

My goal is to make [Client] being [T] so i can pass any struct to apiContainer.

Bellow is a piece of a code that im trying on the playground.

Questions: Is it possible? How can I make it (both on struct and the json.decode line)

import PlaygroundSupport
import UIKit
import Foundation


struct Client: Decodable {
    let name: String
    let postal_code: String
    let city: String
}

struct Meta: Decodable {
    let sucess: String
    let value: String
}

struct apiContainer<T>: Decodable {
    let meta: Meta
    let result: [T]
}

let json = """
{
    "meta": {
        "sucess": "yes",
        "value": "123"
    },
    "result": [
        {
            "name": "Name 1",
            "postal_code": "PC1",
            "city": "City 1",
            "address": "01 Street"
        },
        {
            "name": "Name 2",
            "postal_code": "PC2",
            "city": "City 2",
            "address": "02 Street"
        }
    ]
}
""".data(using: .utf8)!

let converted = try JSONDecoder().decode(apiContainer.self, from: json)

print(converted.result)
print(converted.meta)

Upvotes: 4

Views: 2105

Answers (1)

user28434&#39;mstep
user28434&#39;mstep

Reputation: 6600

struct apiContainer<T>: Decodable

Should be

struct ApiContainer<T: Decodable>: Decodable

And

try JSONDecoder().decode(apiContainer.self, from: json)

Should be

try JSONDecoder().decode(ApiContainer<Client>.self, from: json)

And voilà! It works.

Upvotes: 9

Related Questions