Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

Tags:

swiftui

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()
like image 703
ayelvs Avatar asked May 17 '20 14:05

ayelvs


4 Answers

You just need to add a $:

Toggle(isOn: $character.isSelected){
like image 52
Kuhlemann Avatar answered Oct 16 '22 17:10

Kuhlemann


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

Fixed by adding .wrappedValue:

nameOfBinding.wrappedValue
like image 12
Nelu Avatar answered Oct 16 '22 16:10

Nelu


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()
like image 3
Asperi Avatar answered Oct 16 '22 17:10

Asperi


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

The solution was easy peasy:

.constant(true)
like image 1
oskarko Avatar answered Oct 16 '22 17:10

oskarko