top of page
Writer's pictureDi Nerd Apps

The Beginner's Guide to MVVM in SwiftUI: Easy for Everyone🧑🏿‍💻

Updated: Mar 25, 2023

Are you tired of spaghetti code and complex view controllers in your SwiftUI app?


Well, you’re in luck! In this tutorial, we’ll introduce you to MVVM architecture in SwiftUI and show you how it can help you keep your code organized and your sanity intact.


First, let’s define what MVVM is. MVVM stands for Model-View-ViewModel, and it’s an architectural pattern that separates the presentation logic from the business logic in your app.


The Model represents the data and the business logic, the View represents the UI, and the ViewModel acts as the middleman between the two.


The ViewModel exposes data and commands that the View can bind to, and it translates user actions into commands that the Model can understand.


Now, let’s see how we can implement MVVM in SwiftUI. Here’s an example:

struct UserListView: View {
    @ObservedObject var viewModel: UserListViewModel
    
    var body: some View {
        NavigationView {
            List(viewModel.users) { user in
                Text(user.name)
            }
            .navigationBarTitle("Users")
            .onAppear {
                viewModel.fetchUsers()
            }
        }
    }
}

class UserListViewModel: ObservableObject {
    @Published var users: [User] = []
    
    func fetchUsers() {
        // Fetch users from a data source, e.g. an API or a database
        let users = [User(name: "John"), User(name: "Jane"), User(name: "Bob")]
        self.users = users
    }
}

struct User {
    let name: String
}

In this code, we define a UserListView that displays a list of users.


The view takes in a UserListViewModel as its view model, which is an ObservableObject that contains the users data and the fetchUsers method.


We use the @ObservedObject property wrapper to bind the view model to the view, so that any changes to the view model's @Published properties will trigger an update in the view.





Notice that the UserListView doesn't contain any business logic or data fetching code. Instead, it delegates these responsibilities to the view model.


This separation of concerns makes the code easier to understand and maintain.


Now, let’s see how we can use this view in our app:

struct ContentView: View {
    var body: some View {
        UserListView(viewModel: UserListViewModel())
    }
}

In this code, we define a ContentView that simply displays the UserListView with a new instance of the UserListViewModel. This separates the creation of the view model from the view, making it easier to test and reuse.


And there you have it! You now have a basic understanding of MVVM in SwiftUI. By using this architectural pattern, you can keep your code organized, maintainable, and easy to test.


Plus, you’ll avoid becoming the kind of developer who talks to their code like it’s a person. “Why aren’t you working? Do you hate me?”


We hope you enjoyed this tutorial, and if you have any questions or feedback, please feel free to leave a comment below. Keep coding, and may the force be with you.

11 views0 comments

Recent Posts

See All

Comments


bottom of page