Michael Rowe
Michael Rowe

Reputation: 956

'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??

Upvotes: 6

Views: 11786

Answers (1)

kontiki
kontiki

Reputation: 40489

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.

Upvotes: 6

Related Questions