可编码类的继承 [英] Inheritance of Encodable Class

查看:106
本文介绍了可编码类的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift 4和Xcode 9.2编写程序.我在编写可编码的类(确实是类,而不是结构)时遇到了困难.当我尝试从另一个继承一个类时,JSONEncoder不会从子类(子类)获取所有属性.请看这个:

I am writing a program using Swift 4 and Xcode 9.2. I have faced difficulties with writing encodable class (exactly class, not struct). When I am trying to inherit one class from another, JSONEncoder does not take all properties from sub class (child). Please look at this:

class BasicData: Encodable {

    let a: String
    let b: String

    init() {
        a = "a"
        b = "b"
    }
}

class AdditionalData: BasicData {

    let c: String

    init(c: String) {
        self.c = c
    }

}

let encode = AdditionalData(c: "c")

do {
    let data = try JSONEncoder().encode(encode)
    let string = String(data: data, encoding: .utf8)
    if let string = string {
        print(string)
    }
} catch {
}

它将打印以下内容:{"a":"a","b":"b"}

但是我需要这个:{"a":"a","b":"b","c":"c"}

这看起来像类的属性只是失去了某处,不知何故.

It look like c property of class AdditionalData just lost somewhere and somehow.

问题是:如果我已使用协议Encodable签名了类,那么如何正确地使子类(此类的子类,继承)成为类?

So question is: if I have class signed with protocol Encodable how to make sub class (child of this class, inherit) class properly?

感谢您的帮助或建议.

推荐答案

EncodableDecodable涉及一些代码合成,其中编译器实际上是为您编写代码.当您使BasicData符合Encodable时,这些方法将被写入BasicData类,因此它们不知道子类定义的任何其他属性.您必须在子类中覆盖encode(to:)方法:

Encodable and Decodable involve some code synthesis where the compiler essentially writes the code for you. When you conform BasicData to Encodable, these methods are written to the BasicData class and hence they are not aware of any additional properties defined by subclasses. You have to override the encode(to:) method in your subclass:

class AdditionalData: BasicData {
    let c: String
    let d: Int

    init(c: String, d: Int) {
        self.c = c
        self.d = d
    }

    private enum CodingKeys: String, CodingKey {
        case c, d
    }

    override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.c, forKey: .c)
        try container.encode(self.d, forKey: .d)
    }
}

有关Decodable的类似问题,请参见此问题.

See this question for a similar problem with Decodable.

这篇关于可编码类的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆