I want to be able to convert classes to dictionaries, but I'm having an issue when one class derives from another. Here's an example illustrating the issue:
class Base: Codable {
var b = "base"
}
class Derived: Base {
var d = "derived"
func serializeToDictionary() -> [String: Any]? {
if let data = (try? JSONEncoder().encode(self)) {
return (try? JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as? [String: Any]) ?? [:]
} else {
return nil
}
}
}
let d = Derived()
let dict = d.serializeToDictionary()
dict
only contains one key/value pair - b/"base"
Why does dict
not contain two pairs? Why does it not contain a dictionary item for d/"derived"?