Skip to content

Instantly share code, notes, and snippets.

@memfrag
Created December 17, 2017 21:03
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 memfrag/7f2e5bf0883067cad8eaa67dd9c57e33 to your computer and use it in GitHub Desktop.
Save memfrag/7f2e5bf0883067cad8eaa67dd9c57e33 to your computer and use it in GitHub Desktop.
import Foundation
private class Nothing: Decodable { }
func decodeArray<T, U: Decodable>(_ container: KeyedDecodingContainer<T>, forKey key: T) throws -> [U] {
var unkeyedContainer = try container.nestedUnkeyedContainer(forKey: key)
var objects: [U] = []
while !unkeyedContainer.isAtEnd {
do {
let object = try unkeyedContainer.decode(U.self)
objects.append(object)
} catch let error {
log(error: "Failed to decode [\(U.self)]: \(error.localizedDescription)")
// The unkeyedContainer does not progress to the next item
// so we cheat by decoding any object.
let _ = try? unkeyedContainer.decode([String: Nothing].self)
}
}
return objects
}
func decodeArrayIfPresent<T, U: Decodable>(_ container: KeyedDecodingContainer<T>, forKey key: T) throws -> [U]? {
guard container.contains(key) else {
return nil
}
return try decodeArray(container, forKey: key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment