diff --git a/MVMCore/MVMCore/Models/Model/Model.swift b/MVMCore/MVMCore/Models/Model/Model.swift index e2adaae..44e1025 100644 --- a/MVMCore/MVMCore/Models/Model/Model.swift +++ b/MVMCore/MVMCore/Models/Model/Model.swift @@ -10,7 +10,7 @@ import Foundation public protocol Model: Codable { - static var identifier: String { get set } + static var identifier: String { get } } diff --git a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift index 05fbfa6..cd40a83 100644 --- a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift +++ b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift @@ -24,6 +24,27 @@ public struct ModelRegistry { } } +extension UnkeyedDecodingContainer { + + public mutating func decodeUnKeyedIfPresent(_ type: T.Type, typeCodingKey: C) throws -> T? where T : Decodable { + let meta = try self.nestedContainer(keyedBy: C.self) + guard let type = try meta.decodeIfPresent(String.self, forKey: typeCodingKey) else { + return nil + } + + //get the type + guard let found = ModelRegistry.types[type] else { + throw ModelRegistry.Error.decoderErrorModelNotMapped + } + let model = try self.decode(found) + + guard let m = model as? T else { + throw ModelRegistry.Error.decoderError + } + return m + } + +} extension KeyedDecodingContainer where Key: CodingKey { @@ -48,7 +69,7 @@ extension KeyedDecodingContainer where Key: CodingKey { public func decodeIfPresent(codingKey: KeyedDecodingContainer.Key, typeCodingKey: C) throws -> T? { //get the type string - let meta = try self.nestedContainer(keyedBy: type(of: typeCodingKey), forKey: codingKey) + let meta = try self.nestedContainer(keyedBy: C.self, forKey: codingKey) guard let type = try meta.decodeIfPresent(String.self, forKey: typeCodingKey) else { return nil }