From 77ae83982b180fba63eac8bf919d0479deff1be2 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Fri, 10 Jun 2022 14:21:33 -0500 Subject: [PATCH] added helpers for decodeContext Signed-off-by: Matt Bruce --- .../Models/Extensions/Decoder+UserInfo.swift | 21 +++++++++++++++++++ .../MVMCore/Models/Model/ModelProtocol.swift | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/MVMCore/MVMCore/Models/Extensions/Decoder+UserInfo.swift b/MVMCore/MVMCore/Models/Extensions/Decoder+UserInfo.swift index 686b241..f948056 100644 --- a/MVMCore/MVMCore/Models/Extensions/Decoder+UserInfo.swift +++ b/MVMCore/MVMCore/Models/Extensions/Decoder+UserInfo.swift @@ -111,3 +111,24 @@ extension JSONDecoder { get { return userInfo[.contextKey] as? DecodingContext } } } + +extension KeyedDecodingContainer { + public func decodeContext(_ type: T.Type, forKey key: KeyedDecodingContainer.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(_ type: T.Type, forKey key: KeyedDecodingContainer.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 + } + } +} diff --git a/MVMCore/MVMCore/Models/Model/ModelProtocol.swift b/MVMCore/MVMCore/Models/Model/ModelProtocol.swift index 960f593..addbb48 100644 --- a/MVMCore/MVMCore/Models/Model/ModelProtocol.swift +++ b/MVMCore/MVMCore/Models/Model/ModelProtocol.swift @@ -35,7 +35,7 @@ public protocol ModelProtocol: Codable { extension ModelProtocol { static public func decode(keyedContainer: KeyedDecodingContainer, 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? {