67

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!

3
  • 1
    Projected values (something started with $) can be different in different contexts. Binding projected value in your second case is generated by @ObservedObject, if first case @Published generates publisher projected value. The question is what are you trying to do and why do you put View insider view model?
    – Asperi
    Aug 6, 2020 at 11:24
  • 1
    I am following the MVVM principles that were described on the Ray Wenderlich Sitze (raywenderlich.com/4161005-mvvm-with-combine-tutorial-for-ios). There they put all the routing logic inside the viewmodel of a view (including the instanciation and configuration of views + their models). Thats basically what I am trying to do here.
    – Jan Koch
    Aug 6, 2020 at 12:06
  • Better to follow SwiftUI principals, MVVM isn't really suited to SwiftUI which already solves everything.
    – malhal
    Sep 11, 2020 at 7:31

5 Answers 5

126

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.

8
  • 8
    This should be the accepted answer!
    – obevan
    Feb 25, 2022 at 15:47
  • 3
    That makes so much sense I don't know why I didn't think about it. lol
    – Jayson
    Mar 14, 2022 at 9:37
  • 1
    Can't believe this actually worked Mar 27, 2022 at 19:05
  • 2
    Most people probably have globalSettings.$tutorialView because that's what XCode suggests while you're typing. May 11, 2022 at 15:31
  • 1
    You are a god among men Apr 22 at 21:10
13

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

3
  • 2
    Thanks. I saw that as well but it looks a bit clunky. But I will try it out now :-)
    – Jan Koch
    Aug 6, 2020 at 12:07
  • 2
    I get Cannot find 'self' in scope
    – Ahmadreza
    May 7, 2021 at 15:10
  • I was about to give up on using binding in favor of some closure, but this was exactly what I needed! I had a view model with a published property that it needed to pass as a binding to something else and this did the trick. Thank you!
    – luismgb
    Feb 7 at 15:56
10

I think the important thing to understand here is what "$" does in the Combine context.

What "$" does is to publish the changes of the variable "showPasswordReset" where it is being observed.

when it precedes a type, it doesn't represent the type you declared for the variable (Boolean in this case), it represents a publisher, if you want the value of the type, just remove the "$".

"$" is used in the context where a variable was marked as an @ObservedObject, (the ObservableObject here is LoginViewModel and you subscribe to it to listen for changes in its variables market as publishers)

struct ContentView: View {
       @ObservedObject var loginViewModel: LoginViewModel...

in that context (the ContentView for example) the changes of "showPasswordReset" are going to be 'Published' when its value is updated so the view is updated with the new value.

4

Here is possible approach - the idea to make possible observation in generated view and avoid tight coupling between factory & presenter.

Tested with Xcode 12 / iOS 14 (for older systems some tuning might be needed)

protocol ResetViewModel {
    var showPasswordReset: Bool { get set }
}

struct PasswordResetView<Model: ResetViewModel & ObservableObject>: View {
    @ObservedObject var resetModel: Model

    var body: some View {
        if resetModel.showPasswordReset {
            Text("Show password reset")
        } else {
            Text("Show something else")
        }
    }
}

class LoginViewModel: ObservableObject, Identifiable, ResetViewModel {
    @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(resetModel: self)
    }
}
1
  • That's a very smart idea by just putting the ObservedObject in the view and with that preventing any type issues. I use it to update a progress bar which is monitoring a published progress value in another thread and works perfectly.
    – B Porr
    Feb 16, 2021 at 22:31
-1

For error that states: "Cannot convert value of type 'Binding' to expected argument type 'Bool'" solution is to use wrappedValue as in example below.

If you have MyObject object with property isEnabled and you need to use that as vanilla Bool type instead of 'Binding' then do this myView.disabled($myObject.isEnabled.wrappedValue)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.