Home > Software design >  SwiftUI: 3 attempts using ForEach to iterate array from model data produces entire array
SwiftUI: 3 attempts using ForEach to iterate array from model data produces entire array

Time:08-12

I posted similar code describing a different issue that turned out to be a lack of understanding of ScrollView and List.

Working on the same project, I used ForEach to iterate over an array that came from a struct accessing model data, however the output is the entire array rather than the individual items.

Here is the struct for the model data:

struct OrderInfo: Codable, Identifiable, Hashable {
    
    var id: Int
    var orderNumber: String
    var activeOrderStatus: Bool
    
    var pickupSection: Int
    var pickupStand: String
    var pickupItems: [String]
}

This is my View:

    struct CompletedOrderPickUp: View {
        var completedOrder: OrderInfo
            
        var body: some View {
            ScrollView {
                HStack {
                    Text("Section")
                    Spacer()
                    Text("\(completedOrder.pickupSection)")
                }
                .pickUpDetailsTitleModifier()
            
                HStack {
                    Text("Stand Name")
                    Spacer()
                    Text(completedOrder.pickupStand)
                }
                .pickUpDetailsTitleModifier()
                
                HStack {
                    Text("Order Items")
                    Spacer()
                }
                .pickUpDetailsTitleModifier()

// 3 ATTEMPTS AT ForEach
                ForEach(completedOrder.pickupItems, id: \.self) {
                    Text("\($0)")
                }
                
                ForEach(0..<completedOrder.pickupItems.count, id: \.self) { items in
                    Text(self.completedOrder.pickupItems[items])
                }
                
                ForEach(completedOrder.pickupItems.indices) {
                    Text(self.completedOrder.pickupItems[$0])
                }
            }
        }
    }

What my code produces

From the many articles, questions, and tutorials I've read about arrays and ForEach, none help explain why in this use it produces the entire array instead of the items within. Each lesson assumes that ForEach displays the data on individual rows rather than in one big block.

This is a hard-coded example of what I want it to look like.

What am I missing? Any resource or direction to which you can point me?

CodePudding user response:

The error where pickupItems receives its value, this code is just displaying the value.

Look for where "Cheeseburger, Cheesburger, Cheese Fry Bowl, 24oz Draft Beer. 16oz Draft Beer" comes from.

[“Cheeseburger, Cheeseburger, Fries, Beer”] //Array with 1 string

[“Cheeseburger”, “Cheeseburger”, “Fries”, “Beer”] //Array with multiple strings
  • Related