Created
December 17, 2017 21:03
-
-
Save memfrag/7f2e5bf0883067cad8eaa67dd9c57e33 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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