6 – Beyond MVC: Expanding your app’s architectural layers to extract the app logic from SwiftUI views

Fundamental principles and basic design patterns are not enough when a codebase grows in complexity

If your SwiftUI projects lack structure, starting with basic encapsulation and following the MVC pattern will yield the highest return on investment in readability and maintainability.

These principles are so fundamental that you are going to find them in any software project, regardless of platform or programming language.

However, as a codebase grows, these principles alone are not enough. The modules of a complex app can be further compartmentalized into more fine-grained roles, like:

  • Navigation and deep linking.
  • Networking and authentication.
  • Data storage and databases.
  • Global app state and local state transitions.
  • Error handling.

In a large, complex codebase, these aspects grow sufficiently to warrant their own independent modules, sometimes called layers.

Moreover, internally, these modules might be complex enough to enable further layering, encapsulation, and the adoption of specific design patterns to address recurring problems as the codebase grows.

Expanding the MVC pattern allows you to encapsulate the app’s logic related to a view into a dedicated layer

The growth of roles and subsystems in a large codebase and the iterative application of the Separation of Concerns principle and the Law of Demeter inevitably lead to a multitier architecture with more layers than the three provided by MVC.

These, in turn, lead to the formulation and refinement of more complex design principles and architectural design patterns.

Among these patterns, the two most notable are Model-View-ViewModel and Clean Architecture. While these were primarily developed for enterprise and web applications, their principles are universal and apply to SwiftUI apps as well.

Of particular note in SwiftUI is the MVVM pattern, a derivative of MVC that adds an extra layer containing the app’s business logic for a single app section.

Particularly complex app screens might require business logic that, following the principles we saw in previous lessons, should be moved out of the view layer.

However, given its tight coupling to a specific view, it would be a mistake to move such logic into a shared controller used by other views.

Such a bad practice has, as usual, a related code smell called God (or massive) object, i.e., a type that

  • References too many other types;
  • Has too many unrelated or uncategorized methods; or
  • Some combination of both.

That is why MVVM in SwiftUI has an extra layer.

MVVM and Clean architecture follow the same principles

The dichotomy between MVVM and Clean architecture is only apparent because they refer to the same architectural roles by different names.

While naming can be confusing, once you understand how these roles work in an app’s architecture, you will be able to see their similarities, as any architectural pattern descends from MVC.

For example, VIPER is a widely used derivative of the Clean Architecture for iOS and SwiftUI development.

While its naming conventions might make it look like a completely different pattern, comparing its structure to MVVM’s makes it easy to see the equivalence.

Do this: Move into a view model, a view’s complex app logic that cannot be moved into shared controllers

In a SwiftUI app, some views merely interact directly with shared controllers.

For example, a view summarizing expenses for a specific category can fetch the corresponding transactions from the data controller and chart them directly.

struct TransactionsView: View {
	let category: Category
	@Environment(DataController.self) private var dataController

	var transactions: [Transaction] {
		dataController.fetchTransactions(
			from: .lastYear,
			to: .today,
			category: category
		)
	}

	var body: some View {
		List {
			// ...
			Section {
				ExpensesChart(data: transactions.summaries)
			}
			// ...
		}
		.navigationTitle("\(category.name) Summary")
	}
}

However, other views need to manipulate data further before it’s presented. That logic goes into a view model object.

For example, the main view of our budgeting app can display a section summarizing the expenses for the whole year, the past six months, or the past three months.

This requires additional calculations to fetch the appropriate data from the data controller, which we can encapsulate in a view model.

@Observable
private final class ViewModel {
	var range = SummaryRange.year
	private let dataController: DataController

	init(dataController: DataController) {
		self.dataController = dataController
	}

	var totalExpenses: Decimal {
		expenses.map(\.amount).reduce(0, +)
	}

	var expenses: [Transaction] {
		let startDate = switch range {
			case .year: Date.lastYear
			case .last6: Date.sixMonthsAgo
			case .last3: Date.threeMonthsAgo
		}
		return dataController.fetchTransactions(from: startDate, to: .today)
			.filter { $0.type == .expense }
			.sorted(using: KeyPathComparator(\.category.name))
			.sorted(using: KeyPathComparator(\.date.month))
	}
}

Placing the app business logic for this view into a separate object yields the same benefits as placing domain business logic in model types, making the code more maintainable and testable.

@Test func expenses() async throws {
	let viewModel = ViewModel(
		dataController: DataController(modelContext: .sample))
	#expect(viewModel.totalExpenses == 4673.6)
}

The view can then display the data fetched by the view model.

struct CategoriesView: View {
	@Query(sort: \Category.name) private var categories: [Category]
	@State private var viewModel: ViewModel?
	@Environment(DataController.self) private var dataController

	var body: some View {
		List {
			Balance(amount: categories.balance)
			if let viewModel {
				@Bindable var viewModel = viewModel
				Expenses(
					total: viewModel.totalExpenses,
					summaries: viewModel.expenses.summaries,
					range: $viewModel.range
				)
			}
			Categories(categories: categories)
		}
		.task {
			guard viewModel == nil else { return }
			viewModel = ViewModel(dataController: dataController)
		}
	}
}

The view code is also easier to understand because its structure is clear at a glance, and where the data comes from.

This allows you, for example, to troubleshoot problems more easily. If the user interface does not behave as expected, you can get a high-level view of where the problem might be and dig further into the encapsulated code only when needed.

Encapsulating the formatting logic of views

Both views in this example transform the Transaction values they receive into an array of ExpenseSummary to be displayed by the ExpensesChart view.

extension [Transaction] {
	var summaries: [ExpenseSummary] {
		guard count > 0 else { return [] }
		var summaries: [ExpenseSummary] = []
		var amount: Decimal = 0
		var category = self[0].category.name
		var month = self[0].date.month
		for transaction in self {
			guard transaction.date.month != month
							|| transaction.category.name != category else {
				amount += transaction.amount
				continue
			}
			summaries.append(
				ExpenseSummary(category: category, month: month, amount: amount))
			amount = transaction.amount
			category = transaction.category.name
			month = transaction.date.month
		}
		summaries.append(
			ExpenseSummary(category: category, month: month, amount: amount))
		return summaries
	}
}

The ExpenseSummary type is a simple structure that decouples the ExpensesChart view from the Transaction model, similar to what we did in lesson 3 with simple Swift types.

You can think of the ExpenseSummary structure as a model type for the view, which is why, in some patterns like the Clean Architecture, it is called a view model.

However, as we have seen, in SwiftUI, the name view model is reserved for objects that contain the view’s logic. To avoid confusion, I usually refer to these types as view data, a convention I took from Andy Matuschak.

Back to: The SwiftUI Architecture Audit > Lessons

Leave a Comment