Kazunori Takaishi
Kazunori Takaishi

Reputation: 2388

Can't use @available unavailable with Codable

I would like to apply the available attribute with the renamed and unavailable arguments to a property of struct that conforms to Codable , as shown below:

struct SampleData: Codable {
    @available(*, unavailable, renamed: "newProperty")
    let oldProperty: String
    let newProperty: String
}

But when I tried to build this code , I got a compile error like this:

note: 'oldProperty' has been explicitly marked unavailable here

enter image description here

If a struct does not conform to Codable, it works well.

enter image description here

Does anyone know how to resolve this problem?

And if it is impossible to resolve this, I'd appreciate it if you could tell me why.

Thanks in advance.

Upvotes: 4

Views: 513

Answers (1)

Sweeper
Sweeper

Reputation: 271800

This is because the synthesised Codable conformance is trying to decode/encode oldProperty as well. It can't not do that, because all stored properties has to be initialised, even if they are unavailable.

It will work if you initialise oldProperty to some value, and add a CodingKey enum to tell the automatically synthesised conformance to only encode/decode newProperty:

struct SampleData: Codable {
    @available(*, unavailable, renamed: "newProperty")
    let oldProperty: String = ""
    let newProperty: String
    
    enum CodingKeys: CodingKey {
        case newProperty
    }
}

Actually, depending on the situation, you might be able to convert oldProperty to a computed property, in which case you don't need the coding keys.

struct SampleData: Codable {
    @available(*, unavailable, renamed: "newProperty")
    var oldProperty: String { "" }
    let newProperty: String
}

Upvotes: 5

Related Questions