Kodeco Forums

Design Patterns by Tutorials: MVVM

Learn how and when to use the architecture-slash-design pattern of MVVM in this free chapter from our new book, Design Patterns by Tutorials!


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/34-design-patterns-by-tutorials-mvvm
1 Like

Excellent write up @jstrawn :raised_hands:

Idk how I feel about accessing the View from the ViewModel, it seems like bad practice.

The advantages of using MVVM is to reduce code inside the ViewController, and to allow for unit testing. Perhaps you’ll feel differently after going through some tutorials, or applying the concepts to some real world projects. The one thing I will say is that there is no silver bullet out there. No one pattern can solve all issues. The best thing to do is be open minded to alternative solutions, and using the solution that you are most comfortable with :slight_smile:

Hey, nice writeup. But I have a question.

So there are these relations:
V uses VM
VM configures V

And a final sample that shows how the data from ViewModel gets assigned to parameters in View.
viewModel.configure(view:)

Why not simply pass the ViewModel into View and make these assignments(the configuration of the view) in view’s init method
ie convenience init(viewModel:) ?

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

You can do that too! In fact, that solution does a great job of slimming down the ViewController.

The strength of design patterns often lies in how abstract they can be, which means there are multiple ways you can implement them. So either way, you would still be using MVVM.

Hi, great tutor.

I have a question: Why is annotation creation in view controller?

let image: UIImage
  switch rating {
  case 0.0..<3.5:
    image = UIImage(named: "bad")!
  case 3.5..<4.0:
    image = UIImage(named: "meh")!
  case 4.0..<4.75:
    image = UIImage(named: "good")!
  case 4.75...5.0:
    image = UIImage(named: "great")!
  default:
    image = UIImage(named: "bad")!
  }

I think it would be better to be in view model. View model should be responsible data transformation. What do you think about this?

@jstrawn Do you have any feedback about this? Thank you - much appreciated! :]

Hi Jabson,
Let me know if this thread helps:

You’re correct to think we should do it in a view model or somewhere else besides the viewcontroller. In the chapter after this we use the factory pattern to switch these images, so for tutorial purposes we leave it in the viewcontroller to minimize the amount of refactoring you as the reader have to do. :slight_smile:

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!