首页 > 解决方案 > 无法让 Codable 与继承一起工作

问题描述

我希望能够将类转换为字典,但是当一个类从另一个类派生时我遇到了问题。这是一个说明该问题的示例:

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只包含一个键/值对 - b/"base"

为什么不dict包含两对?为什么它不包含 d/"derived" 的字典项?

标签: iosswiftinheritancecodable

解决方案


推荐阅读