Unable to change Toggles

Newbie to swift.

This code provided th view am after except I am unable to change the Toggles. If I declare State variable individually, it work, but not when the State variable is part of the mySession struct.

Thanks in advance for your help.




struct ContentView: View {

    

    struct mySession: Identifiable {

        var name: String

        let id = UUID()

        @State var selected = true

    }



    @State var pac = false

    @State var atl = false

    @State var ind = false

    @State var sou = false

    @State var art = false



    var sessions = [

        mySession(name: "Pacific"),

        mySession(name: "Atlantic"),

        mySession(name: "Indian"),

        mySession(name: "Southern"),

        mySession(name: "Arctic")

        ]

        



    var body: some View {

            VStack {

                Text("MY CRM")

                    .font(.largeTitle)

                List {

                    ForEach (sessions) {sessions in

                        Toggle(isOn: sessions.$selected) {

                            Text(sessions.name)

                        }

                    }

/*                  Toggle(sessions[0].name, isOn: $pac)

                    Toggle(sessions[1].name, isOn: $atl)

                    Toggle(sessions[2].name, isOn: $ind)

                    Toggle(sessions[3].name, isOn: $sou)

                    Toggle(sessions[4].name, isOn: $art)

*/

                           }

                Spacer()

                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)

            }

        .padding()

    }

}



struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

            .previewInterfaceOrientation(.portrait)

    }

}
Answered by BabyJ in 719251022

Move the @State property wrapper from the selected variable in the mySession struct to the sessions array.

You can then pass a binding directly into the Toggle, like this:

ForEach($sessions) { $session in
    Toggle(isOn: $session.selected) {
        Text(session.name)
    }
}
Accepted Answer

Move the @State property wrapper from the selected variable in the mySession struct to the sessions array.

You can then pass a binding directly into the Toggle, like this:

ForEach($sessions) { $session in
    Toggle(isOn: $session.selected) {
        Text(session.name)
    }
}
Unable to change Toggles
 
 
Q