@Chuck has a bad habit...
I am getting this error when trying to assign a date to a property
// ---------------------------👇🏼 Here! SwiftUI makes a copy.
ForEach(habits, id: \.name) { habit in
HStack {
VStack(alignment: .leading) {
Text(habit.name) // 👈🏼 Here you show the name of the COPY.
Text("\(habit.addedDate.convertToMonthDayYear())")
}
Image(systemName: habit.completedToday ? "checkmark.square.fill" : "square")
// ...snip.....
.onTapGesture {
// 👇 Here! You are trying to change the date of an unmutable copy.
habit.lastCompletionDate = Date()
}
}
View Factory
I like to think of ForEach()
as a factory. It's job is to take some parts and build several views
for you. In your code above, the ForEach()
is building an HStack()
with some content.
Your factory requires a habit
to assemble the parts inside the HStack()
. It's an important skill for you to recognize that you are passing in one habit
at a time from your habits
collection. But when you hand a single habit
to the ForEach()
factory manager, you are NOT providing the actual habit
. Instead you are providing an (unchangable!) copy of the habit
.
Keep Coding
Some other descriptions of the ForEach()
factory.
See -> View Factory
or See -> View Factory
or See -> View Factory
So, ask yourself: In the code snip above what is the ForEach
view factory trying to make?