Skip to content

Instantly share code, notes, and snippets.

@hlung
Last active February 27, 2022 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlung/a9479b63f4669736690fa0776198e25b to your computer and use it in GitHub Desktop.
Save hlung/a9479b63f4669736690fa0776198e25b to your computer and use it in GitHub Desktop.
struct LossyArray<Element: Decodable>: Decodable {
private(set) var elements: [Element]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var elements = [Element]()
if let count = container.count {
elements.reserveCapacity(count)
}
while !container.isAtEnd {
do {
let element = try container.decode(Element.self)
elements.append(element)
}
catch let error {
print("failed to decode \(Element.self): \(error)")
// Decode as the dummy DiscardedElement type to skip it.
_ = try? container.decode(DiscardedElement.self)
continue
}
}
self.elements = elements
}
}
struct DiscardedElement: Codable {}
// Usage example
class AuthorsResponse: Decodable {
let array: [Author]
enum CodingKeys: CodingKey {
case response
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.array = try container.decode(LossyArray<Animal>.self, forKey: .response).elements
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment