I tried to use ForEach()
to generate labels in a list
List {
ForEach(objects) { obj in
Label(obj.id, systemImage: obj.icon)
}
}
The icon of each label is decided by its id so I use lazy var
to define the struct
struct Object: Identifiable {
var id:Int
lazy var icon:String={
// ...
}
}
And create an array for each one
var objects = [
Object(id:1),
Object(id:2),
// ...
]
But it throw an error like Cannot use mutating getter on immutable value: 'obj' is a 'let' constant
CodePudding user response:
Your objects in ForEach(objects) { obj in ... }
will be copied.
Copied value-type object (struct) is immutable, mean its properties could not be changed.
There is no need to use lazy var icon:String = { }
because the icon
value will be changed each time you call it (computation property), and it's not suitable for above immutable object logic.
Try to provide exact value before using in ForEach
struct MyObject: Identifiable {
let id: Int
let icon: String
}
var objects = [
Object(id: 1, icon: "moonphase.waxing.crescent"),
Object(id: 2, icon: "moonphase.waning.crescent"),
// ...
]
CodePudding user response:
Try this:
@State var objects = [
Object(id:1),
Object(id:2),
// ...
]