Last active
July 8, 2018 21:57
-
-
Save MaximKotliar/45d8c075e24a11dde9db37fed9ae609a to your computer and use it in GitHub Desktop.
Adds ability to decode array allowing invalid elements
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
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