user12232037
user12232037

Reputation:

SwiftUI - Increment variable in a ForEach loop

I have this in my ContentView:

List {
    ForEach(items) { Item in
        ItemView(cellColor: self.$cellColor, title: item.title, orderId: "\(item.orderId)")
    }
}

I want to update a variable, let's say by adding 1 to it, on each iteration of the loop, but I can't get SwiftUI to do that. Something like this:

var a: Int = 1
List {
    ForEach(toDoItems) { toDoItem in
        ToDoItemView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
        a = a + 1
    }
}

But that doesn't work. Apologies if I've not asked this in the correct format, This is my first question here!

Upvotes: 5

Views: 8992

Answers (1)

RPatel99
RPatel99

Reputation: 8096

Make a function that returns the view you want in the ForEach and also increments the variable.

struct ContentView: View {
    @State var a: Int = 1
    @State var cellColor: CGFloat = 0.0 // or whatever this is in your code
    var body: some View {
        List {
            ForEach(toDoItems) { toDoItem in
                self.makeView(cellColor: self.$cellColor, title: toDoItem.title, orderId: "\(toDoItem.orderId)")
            }
        }
    }
    func makeView(cellColor: Binding<CGFloat>, title: String, orderId: String) -> ToDoItemView {
        self.a += 1
        return ToDoItemView(cellColor: cellColor, title: title, orderId: orderId)
    }
}

You didn't specify the types of cellColor, title, and orderId, so I just guessed from the context of the rest of your code. You should be able to adjust the types pretty easily, but if not, identify the types of the variables in your question or the comments of this post and I can update my answer (but I'm pretty sure I got the types right).

Edit: Apparently cellColor is a CGFloat, not a Color according to OP's comment, so I updated my code to reflect that.

Upvotes: 7

Related Questions