Skip to Content
Course content

144: MVVM in Swift Applications

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why do I even need a ViewModel? Can't I just put the logic in the View?

I get this question a lot, especially since SwiftUI makes it so easy to throw a few functions right inside your View struct. Sure, it works for a tiny prototype. But as soon as your app grows, you'll hit a wall. If you put your formatting logic, API calls, and state management inside the View, you end up with a "Massive View" that is nearly impossible to test without spinning up the entire UI simulator.

Think of the ViewModel as a translator. Your Model might give you a raw temperature in Kelvin from an API, but your View needs a formatted string like "72°F". If you put that conversion logic in the View, you can't test it in a unit test. If you put it in the ViewModel, you can write a simple test that says: "Given 295.15K, does the ViewModel return '72°F'?"

Here is a quick look at the difference using a weather app example:

// The Model: Pure data
struct Weather {
    let temperatureKelvin: Double
    let condition: String
}

// The ViewModel: The "brains" and translator
class WeatherViewModel: ObservableObject {
    @Published var temperatureText: String = ""
    @Published var conditionText: String = ""
    
    func updateWeather(with weather: Weather) {
        // Logic lives here, away from the UI
        let celsius = weather.temperatureKelvin - 273.15
        self.temperatureText = String(format: "%.0f°C", celsius)
        self.conditionText = weather.condition.capitalized
    }
}

// The View: Just displays what it's told
struct WeatherView: View {
    @StateObject var viewModel = WeatherViewModel()
    
    var body: some View {
        VStack {
            Text(viewModel.temperatureText)
                .font(.largeTitle)
            Text(viewModel.conditionText)
        }
    }
}

How does the View actually "stay in sync" with the ViewModel?

In the old days of UIKit, we had to use delegates or notifications, which felt like wiring a house by hand. In modern Swift, we use the ObservableObject protocol and the @Published property wrapper.

When you mark a property as @Published, Swift automatically creates a publisher. When that value changes, the ViewModel screams, "Hey, I've changed!" and any View observing that ViewModel via @StateObject or @ObservedObject automatically triggers a re-render of its body. It's a reactive loop. I highly recommend sticking to @StateObject when the View is the one creating the ViewModel, and @ObservedObject when the ViewModel is being passed in from a parent.

Where exactly does the network call go? In the Model or the ViewModel?

This is where people usually get tripped up. The ViewModel shouldn't actually *perform* the network request—it should *trigger* it. If you put the URLSession code directly inside your ViewModel, you've just made your ViewModel hard to test because it's now tied to the internet.

The best practice is to introduce a "Service" or "Repository" layer. The ViewModel asks the Service for data, the Service fetches it and returns a Model, and the ViewModel then transforms that Model into something the View can display. It adds one more file to your project, but trust me, it makes your architecture much cleaner.

class WeatherService {
    func fetchWeather() async throws -> Weather {
        // Actual URLSession logic goes here
        return Weather(temperatureKelvin: 295.15, condition: "sunny")
    }
}

class WeatherViewModel: ObservableObject {
    @Published var temperatureText = "--"
    private let service = WeatherService() // The VM depends on the service
    
    func loadWeather() async {
        do {
            let weather = try await service.fetchWeather()
            // Update UI on the main thread
            await MainActor.run {
                self.temperatureText = "\(Int(weather.temperatureKelvin - 273.15))°C"
            }
        } catch {
            // Handle error
        }
    }
}



📋 Practical Task

Exercise: Building a User Profile Dashboard with MVVM

Your task is to move a messy "User Profile" implementation into a proper MVVM architecture. Currently, the View is handling data fetching and string formatting, which makes it bloated.

  • The Model: Create a User struct with firstName, lastName, and joinDate (as a Date object).
  • The ViewModel: Create a UserProfileViewModel that:
    • Holds a User model.
    • Exposes a fullName string (combining first and last names).
    • Exposes a memberSince string (formatting the Date into a readable string like "Joined: January 2023").
    • Includes a function refreshUser() that simulates a network delay using Task.sleep before updating the user data.
  • The View: Create a UserProfileView that displays the fullName and memberSince text. Add a button that calls refreshUser(). Ensure the View does not contain any logic for combining names or formatting dates.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.