Closed irace closed 7 years ago
There's this method on Array that you can use:
[Foo].decode(json, ignoreInvalidObjects: true)
which expands out to:
[Foo?].decoder { try? Foo.decode($0) }(json).flatMap {$0}
If type-inference is desired (e.g it's used a lot) I'd consider something like this
func ignoreInvalids<T: Decodable>(_ json: Any) throws -> [T] { // name?
return try [T].decode(json, ignoreInvalidObjects: true)
}
let objects: [Foo] = try ignoreInvalids(json => "some key")
Say I have an type like:
Given the following JSON:
I want to parse this response such that I end up with an array containing only the two sub-objects that can actually be decoded into
Foo
instances. In other words, I just want to ignore{ "some_non_bar_key": "b" }
and keep the other two.This is pretty easily done with the following code:
But I’m wondering if there’s a more idiomatic way to do this, given functionality that
Decodable
already provides?Thanks!