The first thing that goes wrong in a growing SwiftUI app is that the view starts doing everything: fetching, decoding, validating, formatting and drawing. It works, and it cannot be tested, because every one of those behaviours now requires a rendered view to exercise it.
MVVM separates them. The Model is your data. The View is the SwiftUI struct, which should contain layout and nothing else. The ViewModel is an @Observable class holding the state the view displays and the methods the view calls. The test for whether you have the split right: could you check this logic in a unit test without rendering anything? If not, there is still logic in the view.
Dependency injection is how the ViewModel stays testable. Rather than reaching for URLSession.shared internally, it accepts something conforming to a protocol you define. In production you pass the real implementation; in a test you pass one that returns fixed data instantly. No network, no waiting, no flakiness.
A coordinator owns navigation. Once you drive a NavigationStack with a path array, the decision about where to go next can move out of the view and into one object that knows the whole flow - which is what makes deep links and "return to this exact screen after login" tractable rather than a special case.
import SwiftUI
import Observation
// 1. The dependency, as a protocol the ViewModel owns.
protocol ArticleFetching: Sendable {
func articles() async throws -> [Article]
}
struct LiveArticleService: ArticleFetching {
func articles() async throws -> [Article] { try await fetchArticles() }
}
// A test double - no network, instant, and it can fail on demand.
struct StubArticleService: ArticleFetching {
var result: Result<[Article], Error>
func articles() async throws -> [Article] { try result.get() }
}
// 2. The ViewModel: state and behaviour, no SwiftUI types at all.
@MainActor
@Observable
final class ArticleListModel {
private(set) var articles: [Article] = []
private(set) var failure: String?
private let service: ArticleFetching
// Injected, with a sensible default for production callers.
init(service: ArticleFetching = LiveArticleService()) {
self.service = service
}
func load() async {
do {
articles = try await service.articles()
failure = nil
} catch {
failure = "We could not load the articles."
}
}
}
// 3. The View: layout, and the calls. Nothing else.
struct ArticleListView: View {
@State private var model = ArticleListModel()
var body: some View {
List(model.articles) { Text($0.title) }
.overlay { if let failure = model.failure { Text(failure) } }
.task { await model.load() }
}
}