added helpers for decodeContext

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-06-10 14:21:33 -05:00
parent 071cb16870
commit 77ae83982b
2 changed files with 22 additions and 1 deletions

View File

@ -111,3 +111,24 @@ extension JSONDecoder {
get { return userInfo[.contextKey] as? DecodingContext } get { return userInfo[.contextKey] as? DecodingContext }
} }
} }
extension KeyedDecodingContainer {
public func decodeContext<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T where T : Decodable {
guard let value = try? decodeContextIfPresent(type, forKey: key) else {
throw DecodingError.keyNotFound(key, .init(codingPath: [key], debugDescription: "Key Not Found"))
}
return value
}
public func decodeContextIfPresent<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T? where T : Decodable {
if let value = try self.decodeIfPresent(T.self, forKey: key) {
return value
} else if let decoder = try? superDecoder(forKey: key), let value = decoder.context?.value(forKey: key.stringValue) as? T {
return value
} else {
return nil
}
}
}

View File

@ -35,7 +35,7 @@ public protocol ModelProtocol: Codable {
extension ModelProtocol { extension ModelProtocol {
static public func decode<K: CodingKey>(keyedContainer: KeyedDecodingContainer<K>, codingKey: K) throws -> Self? { static public func decode<K: CodingKey>(keyedContainer: KeyedDecodingContainer<K>, codingKey: K) throws -> Self? {
try keyedContainer.decodeIfPresent(self, forKey: codingKey) try keyedContainer.decodeContextIfPresent(self, forKey: codingKey)
} }
static public func decode(unkeyedContainer: inout UnkeyedDecodingContainer) throws -> Self? { static public func decode(unkeyedContainer: inout UnkeyedDecodingContainer) throws -> Self? {