Created
March 27, 2019 09:23
-
-
Save randomguy0815/d3e00222412b8c8c585f52042b2ac745 to your computer and use it in GitHub Desktop.
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
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