Creating a text-based game for SwiftUI
Wondering why can't I access isSelected in character ForEach loop? It gives the error:
Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'
on the line Toggle(isOn: character.isSelected){
Variable object declaration:
@Binding var characters: [Character]
Code here:
VStack {
    ForEach(characters) { character in               
        HStack{
            VStack(alignment:.leading) {
                Text("\(character.name)")
                    .fontWeight(.bold)
                Text("\(character.description)")
                .lineLimit(10)
                    
            }
            Spacer()
            Toggle(isOn: character.isSelected){
                Text("a")
            }.labelsHidden()
                You just need to add a $:
Toggle(isOn: $character.isSelected){
                        I was getting the same error but in my case the binding itself was a Bool.
Fixed by adding .wrappedValue:
nameOfBinding.wrappedValue
                        A character itself is not bound, it is just a value, it needs to transfer binding from characters via subscript, so here is a solution (.enumerated is used to get access to index and value)
ForEach(Array(characters.enumerated()), id: \.element) { i, character in
    HStack{
        VStack(alignment:.leading) {
            Text("\(character.name)")
                .fontWeight(.bold)
            Text("\(character.description)")
            .lineLimit(10)
        }
        Spacer()
        Toggle(isOn: self.$characters[i].isSelected){ // << here !!
            Text("a")
        }.labelsHidden()
                        In my case, I was in need to pass "true", not a var...
The solution was easy peasy:
.constant(true)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With