Variant Type + Codable

I'm trying to parse the following structure using Codable:

{
  type: "type" // or eg: movie, serie, short, feature
  info: {  /* structure and depending on type*/ }
  state: { /* structure and data depending on type */}
} 

Basically, it's a variant type where the data in info and state depend on the type field. What would be the best approach to model this in Swift by making use of Codable?

Hey, I just ran into a similar Codable modeling issue myself. I'm sure there's a few solutions to this out there, but I ended up with something like this:

enum Media: Decodable {
    case movie(Movie)
    case serie(Serie)
    case short(Short)
    case feature(Feature)
    
    enum CodingKeys: CodingKey {
        case type
    }
    
    init(from decoder: Decoder) throws {
        let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
        let type = try keyedContainer.decode(String.self, forKey: .type)

        let container = try decoder.singleValueContainer()
        switch type {
        case "movie": self = .movie(try container.decode(Movie.self))
        case "serie": self = .serie(try container.decode(Serie.self))
        case "short": self = .short(try container.decode(Short.self))
        case "feature": self = .feature(try container.decode(Feature.self))
        default: throw DecodingError.dataCorruptedError(forKey: .type, in: keyedContainer, debugDescription: "Unknown type")
        }
    }
}

struct Movie: Decodable {
    let info: Info
    let state: State
    
    struct Info: Decodable {}
    struct State: Decodable {}
}

struct Serie: Decodable {
    let info: Info
    let state: State
    
    struct Info: Decodable {}
    struct State: Decodable {}
}

struct Short: Decodable {}

struct Feature: Decodable {}

Hope this is useful! Let me know if you have any questions. :beers:

1 Like
Terms of Service

Privacy Policy

Cookie Policy