SwiftPumpkin

4 of 22 · UI patterns

VIPER

VIPER splits a screen into View, Interactor, Presenter, Entity and Router, connected by protocols.

How it's wired

EventsDisplayUse caseResultsNavigateViewDisplays, forwardsPresenterFormats, decidesRouterNavigationInteractorUse cases + Entities
calls or tellsreports backEvery arrow is a protocol. Each module is assembled by a builder; back-references are weak.
  • View renders.
  • Presenter formats.
  • Interactor runs business rules.
  • Entity is data.
  • Router navigates.
PartOwnsLooks like
ViewRendering, UIKit lifecycle, forwarding user interactionsUIViewController
InteractorBusiness logic, use cases, coordinating domain servicesClass behind a protocol
PresenterPresentation logic, formatting, interpreting user actionsClass, weak view
EntityDomain models independent of presentationStructs
RouterNavigation, transitions, screen constructionWeak 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 logicSubstantial and independently evolving.
DataMultiple data sources and services need orchestration.
OwnershipLong-lived components maintained by multiple engineers.
TestingPresentation and business rules require independent testing.
SymptomThe ViewModel is accumulating too many responsibilities.

Step by step

Contact search

  1. ViewForwards search text to the Presenter.
  2. PresenterCancels any search in flight, waits 250 ms for typing to settle, then asks the Interactor.
  3. InteractorQueries the repository and applies business rules.
  4. PresenterTransforms Contact entities into ContactRow values.
  5. ViewRenders the contact list.

Contact selection

  1. ViewForwards the selected row.
  2. PresenterAsks the Router to open the conversation.
  3. RouterBuilds and pushes the chat screen.

Compared

A contact picker in VIPER

Responsibility
EntityContact identity, phone numbers, eligibility attributes
InteractorRetrieval, search, privacy rules, filtering, identity resolution
PresenterSection grouping, display names, search highlights, empty states, selection state
View / ViewControllerList rendering, scrolling, search input, UIKit lifecycle
RouterOpening 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.

30-second answer

Explain VIPER in 30 seconds.

System designAsked directly

Walk through VIPER's roles. Who owns business logic, who decides to navigate, and who performs the transition?

System designAsked indirectly

The team might replace Core Data next year. How do you keep business logic from depending on the persistence technology?

System designAsked indirectly

Adopting VIPER produced many tiny files per screen and the team is frustrated. How do you adopt it pragmatically?

System designAsked indirectly

You moved a 3,000-line view controller to VIPER, and a few hundred engineers now build on it. What starts to hurt next?

System designAsked directly

In RIBs, the architecture very large apps grew out of VIPER, why would a node have no view at all?

iOS codingAsked indirectly

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?

System designAsked indirectly

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?

Read it in the app's source