Strategy and command patterns

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

Pick the fix

Users export a report as PDF, CSV or JSON, chosen at runtime, and more formats are coming. Which pattern?

Options
Hint 1 of 1

Interchangeable algorithms behind one interface.

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

Show answer

Answer: A Strategy: an Exporter protocol with one implementation per format

Correct. New formats are new types, and callers don't change.

Why not the others?
  • B A switch on the format in every place that exports. Each new format means editing every switch.
  • C Subclass the report screen per format. The format is behaviour, not a kind of screen.
  • D Command objects in an undo queue. Commands help with undo and queues, not choosing algorithms.

30-second answer

Strategy puts interchangeable algorithms behind one protocol, so the caller picks one at runtime, such as different export formats or pricing rules. Command wraps an action as a value with everything needed to run it, so it can be queued, logged, retried or undone. In Swift, strategies are often protocols or closures, and commands are often enums of actions.

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

Explain strategy and command.

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

  • Strategy swaps algorithms
  • Command wraps actions
  • Swift idioms

Deep dive

Closures work as lightweight strategies.

UndoManager registers inverse commands.

Reducer actions in TCA are commands.

Commands persisted to disk become an offline queue.

Common mistakes

  • A giant switch duplicated in many places.
  • Commands that capture mutable shared state.

Senior take & follow-ups

Seniors spot when a growing switch should become a strategy, and actions should become commands.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you implement undo?

    Show hint

    Register the inverse action with UndoManager.

  2. Strategy as protocol or closure?

    Show hint

    Closure for one function, protocol for several.

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