Codable with superclass doesn't work ??

class A: Codable { var x: String? }

class B: A { var y: String? }

When I try to decode class B, the property "y" remains nil even though there is a value for it in the JSON data. If I change it to B: Codable then it works.

When I try to search for a solution, all I can find is people overriding init methods and doing decoding manually in some way. I am having a hard time believeing that this is the right answer.

Surely, coding works across class hierarchies?

What does your JSON look like?

Have you tried pasting a sample of it into https://app.quicktype.io to see what it generates?

When I convert any JSON into objects I always mark it as Codable.

It's possible that B.y = "a value" might be in your JSON, but B itself is not Codable and so cannot be used to code the JSON in the first place.

Class B is Codable as a consequence of extending class A. If you try to mark it Codable explicitly, it's a compiler error. You can mark B Codable instead of A, but then A.x won't decode.

The json just says { "x": "foo", "y": "bar" }. If you put x and y into one class it decodes fine.

Your JSON doesn't require two different classes, and doesn't match what you're trying to do in your code.

What Swift is likely doing is seeing your Codable A class with the x variable, and populating that. The y var is nil because there is no y var in the only Codable class in your code.

If your JSON was:

{
    "A":
    { "x": "foo" },
    "B":
    { "y": "bar" }
}

You'd use something like:

struct RootClass: Codable {
    let a: A
    let b: B

    enum CodingKeys: String, CodingKey {
        case a = "A"
        case b = "B"
    }
}

struct A: Codable {
    let x: String
}

struct B: Codable {
    let y: String
}

Both are Codable, and will correctly parse that updated JSON.

Since your JSON is { "x": "foo", "y": "bar" } you should just be using:

struct RootClass: Codable {
    let x, y: String
}
Codable with superclass doesn't work ??
 
 
Q