I am trying to decode from json objects with generic nested object, and for this I want to pass the type of class dynamically when decoding.
For example, my classes are EContactModel and ENotificationModel which extend ObjectModel (and :Codable)s. ENotificationModel can contain a nested ObjectModel (which can be a contact, notification or other objectmodel).
I have a dictionary of types like this:
static let OBJECT_STRING_CLASS_MAP = [
"EContactModel" : EContactModel.self,
"ENotificationModel" : ENotificationModel.self
...
]
My decoding init method in ENotificationModel looks like this:
required init(from decoder: Decoder) throws
{
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
...
//decode some fields here
self.message = try values.decodeIfPresent(String.self, forKey: .message)
...
//decode field "masterObject" of generic type ObjectModel
let cls = ObjectModelTypes.OBJECT_STRING_CLASS_MAP[classNameString]!
let t = type(of: cls)
print(cls) //this prints "EContactModel"
self.masterObject = try values.decodeIfPresent(cls, forKey: .masterObject)
print(t) //prints ObjectModel.Type
print(type(of: self.masterObject!)) //prints ObjectModel
}
I also tried passing type(of: anObjectInstanceFromADictionary) and still not working, but if I pass type(of: EContactModel()) it works. I cannot understand this, because both objects are the same (ie. instance of EContactModel)
Is there a solution for this?