Factory and builder patterns

Architecture & patterns Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A profile screen can open from a push notification, a deep link or the home list, and needs the same dependencies each time. What helps most?

Options
Hint 1 of 1

Where should wiring live?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A factory, such as ScreenFactory.makeProfile(id:), that wires dependencies in one place

Correct. Every entry point gets the same correctly built screen.

Why not the others?
  • B Build the dependencies separately at each call site. The wiring gets duplicated and drifts.
  • C Make every dependency a singleton. Hidden global state is hard to test.
  • D Subclass the screen for each entry point. The difference is where it starts, not how it behaves.

30-second answer

A factory centralises object creation, so callers ask for 'a profile screen for this id' without wiring dependencies themselves. A builder assembles a complex object step by step. In Swift, builders are often replaced by structs with default parameters, or result builders for DSLs like ViewBuilder, while factories stay useful for wiring screens and swapping implementations in tests.

Practise saying it · 30 s. No recording, just a timer

Explain factory and builder.

Say your answer out loud, then check which of these points you covered:

  • Centralised creation
  • Step-by-step building
  • Swift alternatives

Deep dive

A composition root or app container is a factory for the whole app.

Static factory methods (.preview, .mock) help previews and tests.

Swift's default arguments remove most builder boilerplate.

Result builders power SwiftUI and RegexBuilder.

Common mistakes

  • Builders for objects with two properties.
  • Factories that hide global state.

Senior take & follow-ups

Seniors use factories to keep wiring in one place and know when Swift features make builders unnecessary.

Follow-up questions

Think of your answer first, then open the hint.

  1. Where do you put a factory in a SwiftUI app?

    Show hint

    In the app or feature container that owns dependencies.

  2. What replaces builders in Swift?

    Show hint

    Default parameters and result builders.

Suggest a fix if something here is wrong or out of date.