Created
September 16, 2024 15:24
-
-
Save mrbodich/f712a2a4ab957d3b27153295696f11f4 to your computer and use it in GitHub Desktop.
FeedItem Decoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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