Variable modification in forEach

Hi! I'm trying to do a forEach loop on an array of objects. Here's my code :

ForEach($individus) { $individu in
                                if individu.reussite == true {
                                    individu.score -= 10
                                } else {
                                    individu.score = (individu.levees * 10) + 20 + individu.score
                                }
                            }

I have an error on the code in the 'if' saying that "Type '()' cannot conform to 'View'", but I have no idea on how solving this problem.

This is inside a View, right?

I believe your error is with the $ signs before individus and individu. It looks like you're trying to pass a Binding var, but that's not what you do in this situation.

A few things here:

  • ForEach in SwiftUI is used to iterate over a range, array, or any collection of data to generate multiple child views. You would use ForEach to provide views based on a RandomAccessCollection of some data type. Please review the api doc, it goes into more details with same code snippets.

  • a List or ForEach allows you access the binding for example:

struct User: Identifiable {
    let id = UUID()
    var name: String
    var isActive = false
}

struct ContentView: View {
    @State private var users = [
        User(name: "user1"),
        User(name: "user2"),
        User(name: "user3")
    ]

    var body: some View {
        List {
            ForEach($users) { user in
                Text(user.wrappedValue.name)
                Toggle("isActive", isOn: user.isActive)
            }
        }
    }
}

or

struct ContentView: View {
    @State private var users = [
        User(name: "user1"),
        User(name: "user2"),
        User(name: "user3")
    ]

    var body: some View {
        List($users) { user in
            Text(user.wrappedValue.name)
            Toggle("isActive", isOn: user.isActive)
        }
    }
}
Variable modification in forEach
 
 
Q