diff --git a/MVMCore/MVMCore/Models/Extensions/Decoder.swift b/MVMCore/MVMCore/Models/Extensions/Decoder.swift index 04c0be7..fc54a0d 100644 --- a/MVMCore/MVMCore/Models/Extensions/Decoder.swift +++ b/MVMCore/MVMCore/Models/Extensions/Decoder.swift @@ -16,8 +16,12 @@ extension JSONDecoder: AnyDecoder {} extension PropertyListDecoder: AnyDecoder {} extension Data { - public func decode(using decoder: AnyDecoder = JSONDecoder()) throws -> T { - return try decoder.decode(T.self, from: self) + public func decode(using decoder: AnyDecoder = JSONDecoder(), delegateObject: DelegateObject? = nil) throws -> T { + if let decoder = decoder as? JSONDecoder { + return try decoder.decode(T.self, from: self, delegateObject: delegateObject) + } else { + return try decoder.decode(T.self, from: self) + } } } @@ -35,10 +39,10 @@ extension KeyedDecodingContainerProtocol { } extension Decodable { - public static func decode(jsonDict: [String: Any]) throws -> Self { + public static func decode(jsonDict: [String: Any], delegateObject: DelegateObject? = nil) throws -> Self { let jsonData = try JSONSerialization.data(withJSONObject: jsonDict) do { - return try jsonData.decode() + return try jsonData.decode(delegateObject: delegateObject) } catch { throw JSONError.other(error: error) } @@ -73,6 +77,14 @@ public extension JSONDecoder { } userInfo.updateValue(delegateObject, forKey: key) } + + /// Decodes a top-level value of the given type from the given JSON representation, and adds the delegate object if provided. + func decode(_ type: T.Type, from data: Data, delegateObject: DelegateObject?) throws -> T where T : Decodable { + if let delegateObject = delegateObject { + try add(delegateObject: delegateObject) + } + return try decode(T.self, from: data) + } } public extension Decoder {