ios - 无法让 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" 的字典项?
解决方案
推荐阅读
- c# - 由于 NullReferenceException,汽车不会悬停
- python - django 休息框架。展开字段。属性错误
- spring - @CamelSpringTest 和 @CamelSpringBootTest 有什么区别?
- python - 如何使用列表(例如数据类)将 MultiIndex DataFrame 转换为对象?
- deep-learning - 使用自动编码器网络进行单目深度估计
- sql - 如何在 IN 子句 presto 中提供数组
- java - 两条相同的 assertThrows 行表现不同
- push-notification - 是否有可能从flutter-flow发送推送通知
- r - 使用 R 的分位数回归中没有标准误差输出
- linux - 输入此行后我的mac无法打开