Skip to content

Instantly share code, notes, and snippets.

@emarashliev
Last active November 2, 2022 15:16
Show Gist options
  • Save emarashliev/fcc1b67ebdb6c975c1844bc1e81e0715 to your computer and use it in GitHub Desktop.
Save emarashliev/fcc1b67ebdb6c975c1844bc1e81e0715 to your computer and use it in GitHub Desktop.
struct FailableDecodable<Base: Decodable>: Decodable {
var base: Base?
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
base = try container.decode(Base.self)
} catch let error {
print(error)
}
}
}
struct Game: Codable {
let title: String
let id: String
}
struct MyModel: Codable {
let games: [Game]
enum CodingKeys: String, CodingKey {
case games
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
games = try container
.decode([FailableDecodable<Game>].self, forKey: .games)
.compactMap { $0.base }
}
}
let json = """
{
"games": [
{
"title": "God of War",
"id": "GOT"
},
{
"title": "The Last of Us",
"id": "TLOS"
},
{
"title": "The Witcher 3",
"id": "TW3"
},
{
"title": null,
"id": null
}
]
}
"""
let decoder = JSONDecoder()
let myModel = try decoder.decode(MyModel.self, from: json.data(using: .utf8)!)
print(myModel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment