Skip to content

Instantly share code, notes, and snippets.

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 randomguy0815/d3e00222412b8c8c585f52042b2ac745 to your computer and use it in GitHub Desktop.
Save randomguy0815/d3e00222412b8c8c585f52042b2ac745 to your computer and use it in GitHub Desktop.
struct DummyDecodable: Decodable {}
extension KeyedDecodingContainer {
   
func decodeArrayOmitingInvalidObjects<T: Decodable>(forKey key: KeyedDecodingContainer.Key) -> [T] {
   
guard var nestedUnkeyedContainer = try? self.nestedUnkeyedContainer(forKey: key) else {
return []
}
var result = [T]()
   
while !nestedUnkeyedContainer.isAtEnd {
if let element = try? nestedUnkeyedContainer.decode(T.self) {
result.append(element)
}
else {
// We must decode a failed element with an "empty codable type" 
// which will increment `currentIndex` only when decoding succeeds. 
// This prevents an infinite loop.
_ = try? nestedUnkeyedContainer.decode(DummyDecodable.self)
}
   
}
   
return result
}
   
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment