From 5abda67b00d682da0a5b1352d2c35a8af3717601 Mon Sep 17 00:00:00 2001 From: "Pfeil, Scott Robert" Date: Mon, 11 May 2020 16:14:43 -0400 Subject: [PATCH] delegate object for model decoding functions --- .../MVMCore/Models/Extensions/Decoder.swift | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/MVMCore/MVMCore/Models/Extensions/Decoder.swift b/MVMCore/MVMCore/Models/Extensions/Decoder.swift index 5435b1d..04c0be7 100644 --- a/MVMCore/MVMCore/Models/Extensions/Decoder.swift +++ b/MVMCore/MVMCore/Models/Extensions/Decoder.swift @@ -61,4 +61,26 @@ extension Decodable { } } +public enum DecoderKeyError: Error { + case createKey +} +public extension JSONDecoder { + /// Adds a delegate object to the decoder for use in the model initializers. + func add(delegateObject: T) throws { + guard let key = CodingUserInfoKey(rawValue: "delegateObject") else { + throw DecoderKeyError.createKey + } + userInfo.updateValue(delegateObject, forKey: key) + } +} + +public extension Decoder { + /// Gets a delegate object from the decoder for use in the model initializers. Had to be added before decode. + func get() throws -> T? { + guard let key = CodingUserInfoKey(rawValue: "delegateObject") else { + throw DecoderKeyError.createKey + } + return userInfo[key] as? T + } +}