4 of 22 · UI patterns
VIPER
VIPER splits a screen into View, Interactor, Presenter, Entity and Router, connected by protocols.
How it's wired
- View renders.
- Presenter formats.
- Interactor runs business rules.
- Entity is data.
- Router navigates.
| Part | Owns | Looks like |
|---|---|---|
| View | Rendering, UIKit lifecycle, forwarding user interactions | UIViewController |
| Interactor | Business logic, use cases, coordinating domain services | Class behind a protocol |
| Presenter | Presentation logic, formatting, interpreting user actions | Class, weak view |
| Entity | Domain models independent of presentation | Structs |
| Router | Navigation, transitions, screen construction | Weak navigation controller |
Swift example: contact picker
Consider a simplified messaging app's contact picker. A user searches for contacts and selects someone to open a conversation.
Entity
Pure domain data. No UIKit, presentation or database-specific dependencies.
struct Contact {
let id: String
let name: String
let phoneNumber: String
let isBlocked: Bool
}Interactor
Owns business logic and accesses data through abstract dependencies. It decides which contacts are eligible; it doesn't know how they'll be displayed.
protocol ContactRepository: Sendable {
func fetchContacts() async throws -> [Contact]
}
protocol ContactInteractorProtocol: Sendable {
func searchContacts(_ query: String) async throws -> [Contact]
}
final class ContactInteractor: ContactInteractorProtocol {
private let repository: ContactRepository
init(repository: ContactRepository) {
self.repository = repository
}
func searchContacts(_ query: String) async throws -> [Contact] {
let contacts = try await repository.fetchContacts()
return contacts.filter {
!$0.isBlocked
&& (query.isEmpty || $0.name.localizedCaseInsensitiveContains(query))
}
}
}Presenter
Transforms domain data into presentation-ready information and handles user intent. It decides how contacts are represented, not which are eligible or how they're retrieved.
struct ContactRow {
let id: String
let title: String
let subtitle: String
}
@MainActor
protocol ContactViewProtocol: AnyObject {
func showContacts(_ rows: [ContactRow])
func showError(_ message: String)
}
@MainActor
final class ContactPresenter {
weak var view: ContactViewProtocol?
private let interactor: ContactInteractorProtocol
private let router: ContactRouterProtocol
private var searchTask: Task<Void, Never>?
init(interactor: ContactInteractorProtocol, router: ContactRouterProtocol) {
self.interactor = interactor
self.router = router
}
/// One search in flight at a time: a new keystroke cancels the last
/// search, so a slow old result can never overwrite a newer one.
func didSearch(_ query: String) {
searchTask?.cancel()
searchTask = Task {
try? await Task.sleep(for: .milliseconds(250)) // debounce typing
guard !Task.isCancelled else { return }
do {
let contacts = try await interactor.searchContacts(query)
guard !Task.isCancelled else { return } // superseded while awaiting
let rows = contacts.map {
ContactRow(id: $0.id, title: $0.name, subtitle: $0.phoneNumber)
}
view?.showContacts(rows)
} catch is CancellationError {
// Superseded: stay quiet.
} catch {
view?.showError("Unable to load contacts")
}
}
}
func didSelectContact(_ id: String) {
router.openChat(contactID: id)
}
}View
The view controller becomes a thin UIKit adapter.
final class ContactViewController: UIViewController, ContactViewProtocol {
var presenter: ContactPresenter!
private var rows: [ContactRow] = []
func searchTextDidChange(_ text: String) {
presenter.didSearch(text) // the presenter owns cancellation
}
func showContacts(_ rows: [ContactRow]) {
self.rows = rows
// Reload table view
}
func showError(_ message: String) {
// Present error UI
}
func didSelectRow(at index: Int) {
presenter.didSelectContact(rows[index].id)
}
}Router
Encapsulates navigation and destination construction.
@MainActor
protocol ContactRouterProtocol {
func openChat(contactID: String)
}
@MainActor
final class ContactRouter: ContactRouterProtocol {
weak var navigationController: UINavigationController?
func openChat(contactID: String) {
let controller = ChatViewController(contactID: contactID)
navigationController?.pushViewController(controller, animated: true)
}
}Search cancellation is shown because it's the classic follow-up: without it, a slow early response lands after a fast later one and the list shows the wrong results. Module assembly, table rendering and the destination screen are omitted.
Why VIPER is valuable at scale
- Just as MVC suffers from Massive View Controllers, poorly structured MVVM can suffer from Massive ViewModels.
- A ViewModel can gradually accumulate database queries, network orchestration, caching, eligibility rules, analytics, presentation transformations and navigation.
- VIPER provides explicit architectural homes for these responsibilities, though repositories and other domain services are still needed.
- It pays off when business rules and data implementations need to evolve independently of the UI. An identity or privacy migration, for example, should change behind the Interactor's dependencies without leaking into the presentation layer.
When to choose VIPER
| Business logic | Substantial and independently evolving. |
|---|---|
| Data | Multiple data sources and services need orchestration. |
| Ownership | Long-lived components maintained by multiple engineers. |
| Testing | Presentation and business rules require independent testing. |
| Symptom | The ViewModel is accumulating too many responsibilities. |
Step by step
Contact search
- ViewForwards search text to the Presenter.
- PresenterCancels any search in flight, waits 250 ms for typing to settle, then asks the Interactor.
- InteractorQueries the repository and applies business rules.
- PresenterTransforms Contact entities into ContactRow values.
- ViewRenders the contact list.
Contact selection
- ViewForwards the selected row.
- PresenterAsks the Router to open the conversation.
- RouterBuilds and pushes the chat screen.
Compared
A contact picker in VIPER
| Responsibility | |
|---|---|
| Entity | Contact identity, phone numbers, eligibility attributes |
| Interactor | Retrieval, search, privacy rules, filtering, identity resolution |
| Presenter | Section grouping, display names, search highlights, empty states, selection state |
| View / ViewController | List rendering, scrolling, search input, UIKit lifecycle |
| Router | Opening conversations, group creation flows, contact details |
Expert notes
- Default to MVVM with a router. Reach for VIPER when a component has several independent reasons to change, not when a class is long.
- You can add interactors to MVVM without going full VIPER.
Check yourself
Answer out loud before you reveal. Recall is what makes it stick.
Explain VIPER in 30 seconds.
- VIPER splits a screen into five roles behind protocols: View renders, Presenter formats, Interactor runs business rules, Entity is data, Router navigates.
- It formalizes what MVVM blurs: presentation versus business orchestration.
- That pays off on long-lived components with several independent reasons to change, like a contact picker.
- The cost is five types per screen, so I default to MVVM with a router and use VIPER selectively.
Walk through VIPER's roles. Who owns business logic, who decides to navigate, and who performs the transition?
- The Interactor holds one use case's business logic as a plain object with no UIKit import.
- The Presenter formats results, handles input and decides when to navigate.
- The Wireframe, or Router, owns the view controllers and performs the transition.
- The View is a passive, protocol-backed screen.
- Entities are plain data that only the Interactor touches.
- Splitting decide from perform makes navigation logic testable.
The team might replace Core Data next year. How do you keep business logic from depending on the persistence technology?
- Put a data manager between the Interactor and the store.
- The Interactor talks to a protocol, like
protocol OrderStore { func fetch() async throws -> [Order] }, and Core Data stays behind it, so you can swap the store. - Never hand managed objects up to the Presenter.
- Map them into plain structs and let the type system stop persistence types from leaking across boundaries.
Adopting VIPER produced many tiny files per screen and the team is frustrated. How do you adopt it pragmatically?
- Adopt it incrementally and bend it where it hurts.
- VIPER does create many small objects, and deviating is fine as long as each piece keeps a single responsibility.
- Use it for new features instead of rewriting old ones.
- Build the Interactor first, then the Presenter, then the View, so tested logic exists before any UI.
- Merging a trivial Presenter into a static screen's View is fine.
You moved a 3,000-line view controller to VIPER, and a few hundred engineers now build on it. What starts to hurt next?
- App state still follows the view tree.
- VIPER fixes separation and testing, but business logic leaks into presenters, and there's no way to have a node with logic and no screen.
- At that scale, route on business state instead of screens.
- A deep logic tree can then sit over a shallow view hierarchy, which keeps transitions simple and lets teams own whole subtrees.
In RIBs, the architecture very large apps grew out of VIPER, why would a node have no view at all?
- Some states are pure business logic, like logged in versus logged out, and only decide which child to show.
- A viewless node owns that decision and presents its children through the parent's view controller.
- The gotcha is cleanup.
- Nothing removes those views for you, so its detach hook, like
willResignActive(), must dismiss its children's screens or stale screens stay on the stack.
In a RIBs-style tree, a child node needs the signed-in player's name. A teammate wants an optional on a shared object. What do you do instead?
- Pass it into the child's builder at build time, like
build(withListener: self, playerName: name). - The value is fixed for the module's lifetime, and the child never handles nil for a problem it doesn't own.
- Resolve values as early as you can.
- The child declares a dependency protocol and the parent's component satisfies it, so the compiler checks the wiring instead of a runtime lookup.
Beyond VIPER (RIBs-style): about 40 teams ship into one app, and one feature's failure must not block the core flow. How do you structure the modules?
- Split core from optional.
- Keep a small core, like login, session and the main job flow, under strict review.
- Everything else is a plugin.
- Core exposes a plugin-point protocol and each feature implements it behind a feature flag.
- In an incident you switch off one feature, say the map, and the core flow still works.
- The cost is more boilerplate and slower core reviews.
- It works because features reach the core only through the plugin protocol, so switching one off can't break core code.