1

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"?

TylerP
  • 9,600
  • 4
  • 39
  • 43
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • 1
    See also https://stackoverflow.com/questions/50091036/using-codable-to-set-property-values-doesnt-work-through-inheritance – Rob Napier Jan 12 '21 at 22:37
  • 1
    (The short answer is that you can't get Encodable conformance for free when you inherit. You need to write it yourself, or redesign to use structs and protocols instead, which is the general preference in Swift.) – Rob Napier Jan 12 '21 at 22:39

0 Answers0