added helpers for decodeContext
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
parent
071cb16870
commit
77ae83982b
@ -111,3 +111,24 @@ extension JSONDecoder {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,7 +35,7 @@ public protocol ModelProtocol: Codable {
|
||||
extension ModelProtocol {
|
||||
|
||||
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? {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user