diff --git a/MVMCore/MVMCore/Models/Model/Model.swift b/MVMCore/MVMCore/Models/Model/Model.swift index 8e37837..0de3bdd 100644 --- a/MVMCore/MVMCore/Models/Model/Model.swift +++ b/MVMCore/MVMCore/Models/Model/Model.swift @@ -26,5 +26,19 @@ extension Model { let m = try unkeyedContainer.decodeIfPresent(self) return m } + + static public func mvmencode(keyedContainer: inout KeyedEncodingContainer, codingKey: K, model: Model) throws { + guard let typedModel = model as? Self else { + throw ModelRegistry.Error.encoderError + } + try keyedContainer.encode(typedModel, forKey: codingKey) + } + + static public func mvmencode(unkeyedContainer: inout UnkeyedEncodingContainer, model: Model) throws{ + guard let typedModel = model as? Self else { + throw ModelRegistry.Error.encoderError + } + try unkeyedContainer.encode(typedModel) + } } diff --git a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift index f256e8d..5157d84 100644 --- a/MVMCore/MVMCore/Models/Model/ModelRegistry.swift +++ b/MVMCore/MVMCore/Models/Model/ModelRegistry.swift @@ -127,10 +127,12 @@ extension KeyedEncodingContainer where Key: CodingKey { } ///need instance type as input paramaeter list - public mutating func encodeArray(_ list:[T]?, forKey key:KeyedEncodingContainer.Key) throws { + public mutating func encodeArray(_ list:[Model]?, forKey key:KeyedEncodingContainer.Key) throws { var unkeyedContainer = self.nestedUnkeyedContainer(forKey: key) try list?.forEach({ (model) in - try unkeyedContainer.encode(model) + let typeString = type(of: model).identifier + let type = ModelRegistry.getType(for: typeString) + try type?.mvmencode(unkeyedContainer: &unkeyedContainer, model: model) }) } }