I have the following:
struct myModel: Decodable, Identifiable {
let id = UUID()
let a, b, c: String
}
I'm getting the following warning:
Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten
I don't want to change the id once the data is refreshed, I just want to assign it once. How can I get rid of that warning?
CodePudding user response:
Either declare id
as var
or add CodingKeys
and omit id
.
And please name structs and classes always with starting capital letter
struct MyModel: Decodable, Identifiable {
private enum CodingKeys: String, CodingKey { case a, b, c }
let id = UUID()
let a, b, c: String
}
CodePudding user response:
Right now, myModel
conforms to Codable for archival. When decoding, ID will be set to a new UUID instead of the UUID defined in the 'id' field in the file.
If you want to preserve IDs when decoding the structs (say, if you write it to a file and want the same ID when reading back), remove the inline initializer and write a full initializer that takes a, b, and c as arguments.
If you don't want to preserve IDs when decoding, ignoring the warning and keeping the code as-is is sufficient.