Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Bool' is not convertible to 'Binding<Bool>' in SwiftUI

I have a SwiftUI native Watch app I Am working on. I have a Combine based class that allows me to store `\userDefaults, one of which is a simple toggle.

import SwiftUI  
import Foundation  
import Combine  


class MeetingSetup: BindableObject {  

    let willChange = PassthroughSubject<Void, Never>()  

    var twitterEnabled: Bool = false {  
        didSet {  
            willChange.send()  
        }  
    }  

    init() {  
        let prefs:UserDefaults = UserDefaults(suiteName: "group.com.appname")!  
        twitterEnabled = prefs.bool(forKey: "keyTwitterEnabledBool")  
    }  
} 

In the SwiftUI I am getting the error messages that Bool is not convertible to Binding<Bool>

import SwiftUI  
import Combine  

struct SetupView : View {  

    @ObjectBinding var meetingSetup: MeetingSetup = delegate.meetingSetup  

    var body: some View {  

                HStack{  
                    Toggle(isOn: self.meetingSetup.twitterEnabled){  // <== 'Bool' in not convertible to 'Binding<Bool>'  
                        Text("Twitter")  
                    }  
    }  
} 

I don't understand why this is getting the message since the code is @ObjectBinding, should it not be Binding<Bool> by definition? If not how do I address this correctly??

like image 434
Michael Rowe Avatar asked Jul 21 '19 13:07

Michael Rowe


People also ask

What is binding bool SwiftUI?

What's @Binding in SwiftUI? A binding is essentially a connection between a value, like a Bool, and an object or UI element that displays and changes it, like a slider or text field. The connection is two-way, so the UI element can change the value, and the value can change the UI element.

What is binding string SwiftUI?

Binding is a property wrapper that creates a connection between stored data, and a view that displays and changes that data. It is a two-way connection to a source of truth. It is used to both read the latest value, as well as to set a new value.


1 Answers

You missed the dollar sign:

Toggle(isOn: self.$meetingSetup.twitterEnabled) { ... }

I also noticed that you are using didSetin your @BindableObject, but you should really be using willSet.

And finally, maybe you pasted incompletely, but you are missing a closing bracket in your view.

If you don't know what the dollar sign is for, check the WWDC2019 video Data Flow in SwiftUI.

like image 65
kontiki Avatar answered Jan 03 '23 08:01

kontiki