From a16c56505eb290754ef729a05ae305d43ba286c2 Mon Sep 17 00:00:00 2001 From: panxi Date: Fri, 13 Dec 2019 10:32:32 -0500 Subject: [PATCH] update encode method --- MVMCore/MVMCore/Models/Model/Model.swift | 14 ++++++++++++++ MVMCore/MVMCore/Models/Model/ModelRegistry.swift | 6 ++++-- 2 files changed, 18 insertions(+), 2 deletions(-) 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) }) } }