Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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