refactored create method

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-05-10 14:49:59 -05:00
parent a7e32f3ca4
commit 9bb90b2153
2 changed files with 10 additions and 6 deletions

View File

@ -9,15 +9,15 @@
import Foundation
extension CodingUserInfoKey {
internal static let delegateObjectKey = CodingUserInfoKey(rawValue: "delegateObject")!
internal static let contextKey = CodingUserInfoKey(rawValue: "context")!
public static let delegateObjectKey = CodingUserInfoKey(rawValue: "delegateObject")!
public static let contextKey = CodingUserInfoKey(rawValue: "context")!
}
// MARK: - DelegateObject
public extension JSONDecoder {
/// Adds a delegate object to the decoder for use in the model initializers.
func add(value: Any, for key: CodingUserInfoKey) {
userInfo.updateValue(value, forKey: key)
func add<T: DelegateObject>(delegateObject: T) {
add(value: delegateObject, for: .delegateObjectKey)
}
}
@ -89,11 +89,15 @@ extension Decoder {
}
extension JSONDecoder {
/// Adds a key/value to the decoder for use in the model initializers.
func add(value: Any, for key: CodingUserInfoKey) {
userInfo.updateValue(value, forKey: key)
}
/// Helper method to initialize a JSONDecoder
/// - Parameter delegateObject: Delegate Object
/// - Returns: JSONDecoder
public class func create(delegateObject: DelegateObject? = nil) -> JSONDecoder {
public class func create(with delegateObject: DelegateObject? = nil) -> JSONDecoder {
let decoder = JSONDecoder()
decoder.add(value: DecodingContext(), for: .contextKey)
if let delegateObject = delegateObject {

View File

@ -52,7 +52,7 @@ extension Decodable {
public static func decode(jsonDict: [String: Any], delegateObject: DelegateObject? = nil) throws -> Self {
let jsonData = try JSONSerialization.data(withJSONObject: jsonDict)
do {
let decoder = JSONDecoder.create(delegateObject: delegateObject)
let decoder = JSONDecoder.create(with: delegateObject)
return try jsonData.decode(using: decoder)
} catch {
throw JSONError.other(error: error)