diff --git a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift index 44d76fd..695ecb8 100644 --- a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift +++ b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift @@ -50,18 +50,12 @@ extension KeyedDecodingContainer where Key: CodingKey { /// Decodes to a registered model based on the identifier, optional. public func decodeModelIfPresent(codingKey: KeyedDecodingContainer.Key, typeCodingKey: C) throws -> T? { //get the identifier string - var container: KeyedDecodingContainer? - do { - container = try nestedContainer(keyedBy: C.self, forKey: codingKey) - } catch { - return nil - } - guard let identifier = try container?.decodeIfPresent(String.self, forKey: typeCodingKey) else { + guard let container = try? nestedContainer(keyedBy: C.self, forKey: codingKey), let identifier = try? container.decodeIfPresent(String.self, forKey: typeCodingKey) else { return nil } //get the type - guard let type = ModelRegistry.types[identifier] else { + guard let type = ModelRegistry.getType(for: identifier) else { MVMCoreLoggingHandler.logDebugMessage(withDelegate: "Model not mapped: \(identifier)") throw ModelRegistry.Error.decoderErrorModelNotMapped } @@ -75,32 +69,27 @@ extension KeyedDecodingContainer where Key: CodingKey { return m } - /// Decodes an array of registered model based on the identifiers, optional. +/// Decodes an array of registered model based on the identifiers, optional. public func decodeModelsIfPresent(codingKey: KeyedDecodingContainer.Key, typeCodingKey: C) throws -> [Model]? { + guard var container = try? nestedUnkeyedContainer(forKey: codingKey) else { + return nil + } var models = [Model]() - var container = try nestedUnkeyedContainer(forKey: codingKey) var containerCopy = container - - var i = 0 - let count = container.count ?? 0 - while !container.isAtEnd { - if i < count { - let nestedContainer = try container.nestedContainer(keyedBy: C.self) - if let identifier = try nestedContainer.decodeIfPresent(String.self, forKey: typeCodingKey) { - //get the type - guard let type = ModelRegistry.types[identifier] else { - throw ModelRegistry.Error.decoderErrorModelNotMapped - } - //now get the decoder to use for the type - let decoder = try containerCopy.superDecoder() - let model = try type.init(from: decoder) - models.append(model) + let nestedContainer = try container.nestedContainer(keyedBy: C.self) + if let identifier = try nestedContainer.decodeIfPresent(String.self, forKey: typeCodingKey) { + //get the type + guard let type = ModelRegistry.getType(for: identifier) else { + throw ModelRegistry.Error.decoderErrorModelNotMapped } - i+=1 + //now get the decoder to use for the type + let decoder = try containerCopy.superDecoder() + let model = try type.init(from: decoder) + models.append(model) } } - return models.count > 0 ? models : nil + return models } /// Decodes an array of registered model based on the identifiers.