Reputation: 2388
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
If a struct
does not conform to Codable
, it works well.
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
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