Skip to content

Instantly share code, notes, and snippets.

@juliantejera
Created April 8, 2019 02:52
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 juliantejera/781a566f8832ce9aa7710e07f30127c6 to your computer and use it in GitHub Desktop.
Save juliantejera/781a566f8832ce9aa7710e07f30127c6 to your computer and use it in GitHub Desktop.
Decoding Extensions
extension KeyedDecodingContainer where K : CodingKey {
func decodeArrayWithOptionalElements<T>(_ type: [T].Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> [T] where T : Decodable {
return (try decode([DecodableContainer<T>].self, forKey: key)).compactMap { $0.value }
}
}
extension JSONDecoder {
func decodeArrayWithOptionalElements<T>(_ type: [T].Type, from data: Data) throws -> [T] where T : Decodable {
return (try decode([DecodableContainer<T>].self, from: data)).compactMap { $0.value }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment