Last active
November 2, 2022 15:16
-
-
Save emarashliev/fcc1b67ebdb6c975c1844bc1e81e0715 to your computer and use it in GitHub Desktop.
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
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