Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use @available unavailable with Codable

Tags:

swift

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.

like image 283
Kazunori Takaishi Avatar asked Oct 17 '25 11:10

Kazunori Takaishi


1 Answers

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
}
like image 51
Sweeper Avatar answered Oct 19 '25 05:10

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!