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!

1
  • What do you mean on each iteration of the loop? ForEach is a builder. Can you explain more please? Commented Oct 17, 2019 at 10:18

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for this. The only issue with the code is cellColor needs to be a CGFloat: Cannot convert value of type 'Binding<Color>' to expected argument type 'Binding<CGFloat>'
All you have to do is change the code from Binding<Color> to Binding<CGFloat> 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
You do not have error "Modifying state during view update, this will cause undefined behavior."
doesn't work, for the reason Michael Ziobro just stated. Shouldn't have a green checkmark. I'll post a better way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.