Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'

Tags:

When trying to compile the following code:

class LoginViewModel: ObservableObject, Identifiable {
    @Published var mailAdress: String = ""
    @Published var password: String = ""
    @Published var showRegister = false
    @Published var showPasswordReset = false

    private let applicationStore: ApplicationStore

    init(applicationStore: ApplicationStore) {
        self.applicationStore = applicationStore
    }

    var passwordResetView: some View {
        PasswordResetView(isPresented: $showPasswordReset) // This is where the error happens
    }
}

Where PasswordResetView looks like this:

struct PasswordResetView: View {
    @Binding var isPresented: Bool
    @State var mailAddress: String = ""
    
    var body: some View {
            EmptyView()
        }
    }
}

I get the error compile error

Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'

If I use the published variable from outside the LoginViewModel class it just works fine:

struct LoginView: View {
    @ObservedObject var viewModel: LoginViewModel

    init(viewModel: LoginViewModel) {
      self.viewModel = viewModel
    }
    
    var body: some View {
            PasswordResetView(isPresented: self.$viewModel.showPasswordReset)
    }
}

Any suggestions what I am doing wrong here? Any chance I can pass a published variable as a binding from inside the owning class?

Thanks!

like image 976
Jan Koch Avatar asked Aug 06 '20 11:08

Jan Koch


2 Answers

** Still new to Combine & SwiftUI so not sure if there is better way to approach **

You can initalize Binding from publisher.

https://developer.apple.com/documentation/swiftui/binding/init(get:set:)-6g3d5

let binding = Binding(
    get: { [weak self] in
        (self?.showPasswordReset ?? false)
    },
    set: { [weak self] in
        self?.showPasswordReset = $0
    }
)

PasswordResetView(isPresented: binding)

like image 193
k-thorat Avatar answered Sep 18 '22 16:09

k-thorat


Not sure why the proposed solutions here are so complex, when there is a very direct fix for this.

Found this answer on a similar Reddit question:

The problem is that you are accessing the projected value of an @Published (which is a Publisher) when you should instead be accessing the projected value of an @ObservedObject (which is a Binding), that is: you have globalSettings.$tutorialView where you should have $globalSettings.tutorialView.

like image 20
Big_Chair Avatar answered Sep 20 '22 16:09

Big_Chair