51

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()

4 Answers 4

45

In my case, I was in need to pass "true", not a var...

The solution was easy peasy:

.constant(true)
Sign up to request clarification or add additional context in comments.

1 Comment

For me too, I needed this for PreviewProvider struct.
22

I was getting the same error but in my case the binding itself was a Bool.

Fixed by adding .wrappedValue:

nameOfBinding.wrappedValue

Comments

15

You just need to add a $:

Toggle(isOn: $character.isSelected){

2 Comments

Then your „@Binding var“ is at the wrong position or you mistyped the variable name.
You can't use this in a ForEach loop.
8

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()

1 Comment

Thank you Asperi, I think this should be the accepted answer. ( When Foreach and Binding combined together. )

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.