Group Group Group Group Group Group Group Group Group

Public viewModel issues



I have a question about implementation of BindableType protocol.
In book, it looks like this:

protocol BindableType {
  associatedtype ViewModelType

  var viewModel: ViewModelType! { get set }

  func bindViewModel()

So, ViewController which conforms to this protocol will have public var viewModel: TasksViewModel! property.
I’m not sure if it is a good solution to make public var as a viewModel.

Why is viewModel binding made like this and not with UIViewController’s custom init method with viewModel as a parameter, for example?
Is it the best possible approach to bind viewModel with UIViewController for MVVM architecture in Swift?


@fpillet Can you please help with this when you get a chance? Thank you - much appreciated! :]


I agree that this is not an ideal solution, as I don’t like force-unwrapping types. This is however what I found to work best in all situations, including when you reanimate view controllers from a storyboard (in this case you don’t have access to the constructor).

This is not cast in stone! You may want to implement a different version of the protocol if you always call the UIViewController initializer. In this case you could pass the VM to the init method.

Feel free to use this chapter more as a guide on techniques, and adapt it to suit your needs.

Hope this helps,