DevPrep

All topics › Design patterns

Builder: why use it in Swift when you have default parameters?

Middle PRO

The gist

Builder is step-by-step construction of a complex object, separated from its final representation. In Java and Objective-C it largely made up for the lack of named parameters and default values. In Swift that part is covered by init with defaults and the memberwise init of structs: for a struct Toast with var duration: Duration = .seconds(2) and var haptic = false, the call Toast(title: "Saved", haptic: true) already reads like a builder, and no separate type is needed.

Builder is justified when the object is assembled in stages in different places (a base configuration plus refinements), when there are invariants between fields to check at the end (build() throws), or when you need a declarative DSL or convenient test data.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store