@Binding and ForEach in SwiftUI
You can use something like the code below. Note that you will get a deprecated warning, but to address that, check this other answer: https://stackoverflow.com/a/57333200/7786555
import SwiftUIstruct ContentView: View { @State private var boolArr = [false, false, true, true, false] var body: some View { List { ForEach(boolArr.indices) { idx in Toggle(isOn: self.$boolArr[idx]) { Text("boolVar = \(self.boolArr[idx] ? "ON":"OFF")") } } } }}
⛔️ Don't use a Bad practice!
Most of the answers (including the @kontiki accepted answer) method cause the engine to rerender the entire UI on each change and Apple mentioned this as a bad practice at wwdc2021 (around time 7:40)
✅ Swift 5.5
From this version of swift, you can use binding array elements directly by passing in the bindable item like:
⚠️ Note that Swift 5.5 is not supported on iOS 14 and below but at least check for the os version and don't continue the bad practice!
In SwiftUI, just use Identifiable structs instead of Bools
struct ContentView: View { @State private var boolArr = [BoolSelect(isSelected: true), BoolSelect(isSelected: false), BoolSelect(isSelected: true)] var body: some View { List { ForEach(boolArr.indices) { index in Toggle(isOn: self.$boolArr[index].isSelected) { Text(self.boolArr[index].isSelected ? "ON":"OFF") } } } }}struct BoolSelect: Identifiable { var id = UUID() var isSelected: Bool}