MessagePack icon indicating copy to clipboard operation
MessagePack copied to clipboard

crash when encoding classes that have multiple CodingKeys because of inheritance

Open meeloo opened this issue 3 years ago • 0 comments

Hi!

I have a bit of inheritance in my codable objects and MessagePack crashes when encoding one of these. I could simplify the code to reproduce the crash to this:

func testMessagePack() {
        do {
            let testerB = TesterB()

            let encoder = MessagePackEncoder()
            let data = try encoder.encode(testerB)
        } catch {
            return
        }
    }
}

class TesterA: Codable {
    var fun = 1
}

class TesterB: TesterA {
    enum CodingKeys: CodingKey {
        case foo
    }
    var foo = 2

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

I checked the code and saw there could be only one container. What would be the best way to add support for any number of containers? I was thinking of just storing an array of them and just set container to the array.last, what do you think?

Cheers,

S.

meeloo avatar Sep 22 '21 21:09 meeloo