I completed this successfully. However as i refactored my code on the Activity View file (which shows the name of the habit, its description and allows you to increase how many times you've completed it), i ran into the below error:
ForEach<Array<Habit>, UUID, NavigationLink<Text, Never>>: the ID xyz occurs multiple times within the collection, this will give undefined results!
This will happen if I increase the completion count on the activity before getting its index (required in order to insert a copy of the updated activity struct with the new completion count). The effect is that if I run the app this way, once i go into the detail view and increase completion count, the above error shows in the console. Then if i go back to the main content view i might run into another copy of the same detail view, and now the top entry on my list has the same as the one i just modified
Relevant code
ContentView:
NavigationStack{
List{
ForEach(habitList.list) {habit in
NavigationLink(value: habit) {
Text("\(habit.name) id: \(habit.id)")
}
}
.onDelete(perform: removeItems)
}
Activity View that works:
Button("Completed this today") {
let index = habits.list.firstIndex(of: habit)
habit.completions += 1
let habitCopy = habit
habits.list[index ?? 0] = habitCopy
}
Activity View that doesn't work:
Button("Completed this today") {
habit.completions += 1
let index = habits.list.firstIndex(of: habit)
let habitCopy = habit
habits.list[index ?? 0] = habitCopy
}
Struct:
struct Habit: Identifiable, Hashable, Codable, Equatable {
var id = UUID()
var name: String
var description: String
var completions: Int
}
I sort of understand that the issue is a result of modifying the original Habit and breaking how the id: works in the ForEach, something goes wrong with its UUID, but was hoping someone here can explain the issue more concretely.
Thanks!