Swift Xcode12、「Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten」、解消したい
Warningになるコード
struct Musician: Codable, Identifiable {
let id = UUID()
let name: String
let instrument: String
}
上記のJSON(一部)
idはSwiftUIでForEachをしたい為に必要(使わない方法もありますが)
"musicians": [
{
"name": "村上\"ポンタ\"秀一",
"instrument": "Drum"
},
{
単純にvarに変えるだけだは、JSON読込(というかデコード)でエラーになります。
解消方法
Developer Forumsにやりとりがありました。
最後の方法はダメでした。
https://developer.apple.com/forums/thread/651802
struct Musician: Codable, Identifiable {
var id = UUID()
let name: String
let instrument: String
enum CodingKeys: String, CodingKey {
case name
case instrument
}
}
CodingKeyは「エンコードやデコードのキーとして使用できるタイプ」設定するプロトコルです。





