Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 146 ยท Advanced Swift

Design Patterns in Swift

Learn the classic design patterns the Swift way - singleton, factory, builder, strategy, delegate, observer and adapter - with protocols, value types and closures, and runnable examples.

A design pattern is a named solution to a problem that keeps coming back. "I need exactly one of these", "I want to swap the algorithm at run time", "this old type does not fit the interface my code expects". The names matter because they let you say a lot in a few words: "that is a strategy" tells another developer how the code is shaped before they read a line of it.

Most pattern books were written for languages where everything is a class. Swift gives you protocols, value types, closures and enums with payloads, and these often make a pattern much smaller than its textbook version. A strategy can be a closure. A builder can be a struct with default values. In this lesson you meet seven patterns, see the Swift form of each, and learn when the lighter Swift alternative is the better choice. You should know protocols, closures and classes.

Singleton: exactly one instance

A singleton is a type with one shared instance that everyone uses. In Swift the idiom is a static let shared plus a private init. Swift initializes a static let lazily and thread-safely, exactly once, the first time it is touched, so no locking code is needed for the creation itself.

Since Swift 6 the compiler also checks that shared state is safe to touch from many threads. A singleton that holds mutable data needs protection: an actor, or a Mutex from the Synchronization module as below.

Swift A thread-safe singleton and its testable form

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output shows that "AppSettings created" appears only after "before first use": creation is lazy. The last three lines show the point of the exercise. Code that reads AppSettings.shared directly can only be tested against the real thing, with whatever state earlier tests left behind. Code that receives a SettingsReading can be given a fake.

Singletons are convenient, and they are overused. Use one for something that is truly unique to the process (a logger, a cache, an app-wide configuration), keep its mutable state protected, and let the code that uses it accept it as a parameter. The more of your code that names .shared directly, the harder it is to change later.

Factory: ask for a kind, get an object

A factory hides which concrete type is created. The caller says what it wants, the factory decides how. This is useful when the choice depends on input (a file extension, a configuration value, a server response) and you want that decision in one place.

Builder: construct step by step

A builder assembles a complex object through a series of small calls, which reads well when there are many optional parts. In Swift, the first thing to try is a struct with default property values, because Swift lets callers override only what they need. A true builder type earns its place when the steps have an order, need validation, or produce a different type at the end.

Swift Factory and builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The factory returns any Shape, so callers never see Circle or Rectangle, and adding a new kind means editing one switch. Notice that a square is produced as a Rectangle: a factory can map several requests onto one type. The builder works because RequestBuilder is a struct: every method copies self, changes the copy and returns it, so a half-finished builder can be reused as a starting point without surprises. The last line shows why Swift code rarely needs the pattern for simple cases: default values plus labelled arguments already do the job.

Strategy: swap the algorithm

A strategy puts an interchangeable algorithm behind one interface. Checkout code does not care how a discount is computed, only that something can turn a price into a lower price. In Swift you can express a strategy as a protocol with several conforming types, or simply as a function type, since closures are values.

Delegate: hand decisions to someone else

The delegate pattern is everywhere in Apple's frameworks. One object does a job and reports events (or asks questions) through a protocol that another object implements. The delegate property is almost always weak, because the delegate usually owns the object that talks to it, and a strong reference back would create a retain cycle (deinit and ARC). That is why delegate protocols are marked AnyObject.

Observer: many listeners, one source

An observer setup lets any number of listeners subscribe to events without the source knowing who they are. In Swift you can build one with an array or dictionary of closures, as below, use NotificationCenter from Foundation, AsyncStream for async code, or the @Observable macro in SwiftUI (observation).

Swift Strategy, delegate and observer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The strategy is swapped at run time by assigning a new value to checkout.strategy, and the totals are 8000, 7200 and 7000. The closure dictionary shows the lighter form, and sorted(by:) is a strategy you already use. In the delegate part, Screen receives two progress calls and the finish call. The observer example returns a token (here an Int) from subscribe so a listener can leave again: after unsubscribe, only B hears "again". Forgetting to unsubscribe is the classic observer leak, because the bus keeps every closure alive.

Adapter: make one interface fit another

An adapter lets a type you cannot or do not want to change work where a different interface is expected. Perhaps a legacy sensor reports Fahrenheit, but your display code expects a TemperatureSource in Celsius. You can write a wrapper struct, or in Swift often an extension that adds the conformance directly.

Swift Adapter: wrapper and extension

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both calls print Now: 37.0 C. Choose the wrapper when you need to add state or when the type is not yours and you do not want your conformance visible everywhere; choose the extension when a plain conformance is enough. Extensions are described in extensions in depth.

Choosing a pattern

Problem Pattern Often simpler in Swift
One shared object Singleton pass the dependency in; keep shared as a default
Hide which type is created Factory a static function or an enum with switch
Many optional parts Builder a struct with default values
Swap an algorithm Strategy a closure parameter
Report events to one owner Delegate a closure property, for a single callback
Notify many listeners Observer NotificationCenter, AsyncStream, @Observable
Fit an old interface Adapter a protocol conformance in an extension

Patterns are tools for recognizing a shape, not goals. If you find yourself adding a protocol, a factory and a builder to a ten-line feature, the pattern is working against you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which two pieces make the standard Swift singleton idiom?

    A static let is initialized lazily and exactly once, thread-safely. The private initializer stops other code from creating a second instance.
  2. 2. Why is code that calls AppSettings.shared directly hard to unit-test?

    If the function reaches for the global itself, the test gets the real object and its leftover state. Accepting a protocol parameter lets the test pass a fake, and production code can still default to .shared.
  3. 3. Why is a delegate property normally declared weak?

    A strong reference in both directions keeps both objects alive forever. weak breaks the cycle, and the protocol is marked AnyObject so that weak is allowed.
  4. 4. In Swift, what is often a lighter replacement for a strategy protocol with several conforming types?

    Closures are values, so a (Int) -> Int parameter can carry the algorithm without declaring a type for each variant.
  5. 5. What typical mistake makes an observer setup leak memory?

    The event source holds a strong reference to every closure it was given. Without an unsubscribe step (or weak capture) those closures and what they captured live as long as the source.

Summary

  • A design pattern names a recurring shape; Swift's protocols, closures and value types often make it smaller.
  • Singleton: static let shared plus private init, protect mutable state with an actor or Mutex, and accept the dependency as a parameter for tests.
  • Factory centralizes the choice of concrete type; builder assembles complex values step by step, and a struct with defaults often replaces it.
  • Strategy swaps an algorithm through a protocol or a closure.
  • Delegate uses a protocol and a weak reference; observer lets many subscribers listen and needs an unsubscribe path.
  • Adapter makes an existing type fit an expected protocol, by wrapper or by extension.

Next: App Architecture: MVC, MVVM and Clean Boundaries