Hi there,
currently I try to practice on JSON data and I stumbled across following issue:
I have a JSON file which holds an item, which itself holds several items, which themselves hold several items. Something like
ItinaryITEM
- HeaderITEM 1
- Item 1
- Item 2
- HeaderITEM 2
- Item 1
- Item 2
class ItinaryItem: Codable, Identifiable {
var name: String
var id: Int
var headerItem: [HeaderItems]
}
class HeaderItems: Codable, Identifiable {
var name: String
var id: Int
var complete: Bool
var items: [Item]
}
class Item: Codable, Identifiable {
var name: String
var id: Int
var amount: Int
var complete: Bool
}
I want to show that data in a List view. For that, I created a
LIST
ForEach (itinaryItem)
ForEach(headerItem)
ForEach(item)
For the final item, I created a separate view.
List {
ForEach(itinaryItems) { item in
Section(header: Text(item.name)) {
ForEach(item.headerItem) { header in
VStack (alignment: .leading, spacing: 7) {
Text(header.name)
.font(.title)
ForEach(header.items) { finalItem in
FinalItemView(completed: finalItem.complete, amount: finalItem.amount, name: finalItem.name)
}
}
}
}
}
}
struct FinalItemView: View {
@State var completed: Bool
var amount: Int
var name: String
var body: some View {
HStack {
Text(String(amount))
Text(name)
Spacer()
Button {
completed.toggle()
} label: {
completed == false ? Image(systemName: "circle").foregroundColor(.gray) : Image(systemName: "checkmark.circle.fill").foregroundColor(.blue)
}
}
.font(.title2)
.padding(.leading)
}
}
when I run this code, all details are shown correctly, as written in the JSON file.
Note that the item.complete BOOL variable is correctly shown for the individual items. But when I click on one item, I was expecting to flip the BOOL only for that specific item. But in reality, the Bool is flipped for all 3 items.
For example, I click on the circle (which is the button) next to the “1 Mask”, but instead of just getting a blue checkmark on that line (which means all 3 items below the Primary Items should have blue checkmarks), the checkmarks on the other lines disappear.
Why is the view correctly reading the initial Bool value of each item and displays it, but as soon as I toggle the Bool value, all Bool values of the ForEach loop are toggled?
What does the trick to just check one item, and not all three in that ForEach loop?