Decodable warning unexpectedly silenced by CodingKeys presence

I am getting expected warning below:

struct Test: Codable {
    var foo = 1
    let bar = 2 // Warning: Immutable property will not be decoded because it is
                // declared with an initial value which cannot be overwritten
    
    // getting the warning above unless below is uncommented:

    // enum CodingKeys: CodingKey, Sendable {
    //    case foo, bar
    // }
}

However if I uncomment the CodingKeys lines - the warning disappears. What's the rationale to not show the warning in this case?

1 Like

it looks like the rationale is outlined in this commentary within the implementation. specifically the case you've identified seems to be 2. (c), which states:

If the type is Codable, do nothing. This is because removing the key will break encoding which is most likely not what the user expects.

there is some more motivation in the associated PR and a past thread.

1 Like

Thank you for the links!

Although... the immutable property will still not be decoded!

it seems if you declare the Codable conformance via an extension you'll still get the warnings:

struct Test {
    var foo = 1
    let bar = 2 // ⚠️
}

extension Test: Codable {}

i haven't thought about it enough to have an opinion on whether the diagnostic makes sense to always emit, but it is a bit surprising that the behavior isn't consistent.

1 Like