5

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!

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278

1 Answers1

6

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.

RPatel99
  • 7,448
  • 2
  • 37
  • 45
  • Thank you for this. The only issue with the code is cellColor needs to be a CGFloat: Cannot convert value of type 'Binding' to expected argument type 'Binding' –  Oct 18 '19 at 06:18
  • All you have to do is change the code from `Binding` to `Binding` like the error says then... Like I said in the post, you didn't say in your question what the type for all the variables were so I had to guess. See my edit. @Nick – RPatel99 Oct 18 '19 at 13:16
  • You do not have error "Modifying state during view update, this will cause undefined behavior." – Michał Ziobro Nov 27 '19 at 15:50
  • 1
    doesn't work, for the reason Michael Ziobro just stated. Shouldn't have a green checkmark. I'll post a better way. – johnrubythecat Jun 29 '21 at 20:30