Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MaximKotliar/45d8c075e24a11dde9db37fed9ae609a to your computer and use it in GitHub Desktop.
Save MaximKotliar/45d8c075e24a11dde9db37fed9ae609a to your computer and use it in GitHub Desktop.
Adds ability to decode array allowing invalid elements
extension KeyedDecodingContainer {
struct Safe<Base: Decodable>: Decodable {
public let value: Base?
public init(from decoder: Decoder) throws {
do {
let container = try decoder.singleValueContainer()
self.value = try container.decode(Base.self)
} catch {
self.value = nil
}
}
}
func decode<T: Decodable>(_ type: [T].Type, forKey key: KeyedDecodingContainer.Key, allowInvalidElements: Bool) throws -> [T] {
guard allowInvalidElements else {
return try decode(type.self, forKey: key)
}
let decoded = try decode([Safe<T>].self, forKey: key).compactMap { $0.value }
return decoded
}
func decodeIfPresent<T: Decodable>(_ type: [T].Type,
forKey key: KeyedDecodingContainer.Key,
allowInvalidElements: Bool) throws -> [T]? {
guard allowInvalidElements else {
return try decodeIfPresent(type.self, forKey: key)
}
let decoded = try decodeIfPresent([Safe<T>].self, forKey: key)?.compactMap { $0.value }
return decoded
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment