Skip to content

Instantly share code, notes, and snippets.

@mrbodich
Created September 16, 2024 15:24
Show Gist options
  • Save mrbodich/f712a2a4ab957d3b27153295696f11f4 to your computer and use it in GitHub Desktop.
Save mrbodich/f712a2a4ab957d3b27153295696f11f4 to your computer and use it in GitHub Desktop.
FeedItem Decoder
import Foundation
enum FeedItem {
case article(Article)
case ad(Ad)
}
struct Article: Decodable {
let id: UInt
let title: String
}
struct Ad: Decodable {
let id: UInt
let unitId: String
}
//FeedItem+Decodable.swift
extension FeedItem: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(ItemType.self, forKey: .type)
switch type {
case .article: self = .article(try container.decode(Article.self, forKey: .data))
case .ad: self = .ad(try container.decode(Ad.self, forKey: .data))
}
}
enum CodingKeys: CodingKey {
case type
case data
}
enum ItemType: String, Codable {
case article = "article"
case ad = "ad_unit"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment