update encode method

This commit is contained in:
panxi 2019-12-13 10:32:32 -05:00
parent 5fcbe414ec
commit a16c56505e
2 changed files with 18 additions and 2 deletions

View File

@ -26,5 +26,19 @@ extension Model {
let m = try unkeyedContainer.decodeIfPresent(self)
return m
}
static public func mvmencode<K:CodingKey>(keyedContainer: inout KeyedEncodingContainer<K>, 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)
}
}

View File

@ -127,10 +127,12 @@ extension KeyedEncodingContainer where Key: CodingKey {
}
///need instance type as input paramaeter list
public mutating func encodeArray<T:Model>(_ list:[T]?, forKey key:KeyedEncodingContainer<K>.Key) throws {
public mutating func encodeArray(_ list:[Model]?, forKey key:KeyedEncodingContainer<K>.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)
})
}
}