Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 146 ยท Protocols and Generics

Generic Patterns

Learn reusable Swift generic patterns - Result-like enums with map and flatMap, generic collections, protocols with Self requirements, phantom types and generic memoization, with runnable code.

Once you know the syntax of generics, the next skill is recognizing the shapes that appear again and again in good Swift code. A handful of patterns cover a surprising amount of ground: a type that is either a value or an error, a collection written once for every element type, a protocol that talks about its own conforming type, and a type parameter that is never stored but still prevents mistakes.

This lesson builds each of them from scratch. You will meet the same ideas in the standard library (Result, Optional, Array, Equatable) and in frameworks, and after writing your own versions they stop being magic. It assumes Generics and Associated Types.

Pattern 1: a Result-like type

The standard library has Result<Success, Failure>, covered in The Result Type. Building a miniature version shows how generic enums with payloads work, and why map and flatMap exist.

Swift A generic Outcome enum with map and flatMap

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 chain reads top to bottom: parse, validate, double. If any step fails, the later steps are skipped and the failure travels to the end. The output is 16 -> success(32), then -4 -> failure(negative(-4)), then abc -> failure(notANumber("abc")). Note the two type parameters: Value is free, Problem is constrained to Error. map introduces a third, NewValue, only for that method.

The rule for naming: map takes a function that returns a plain value and wraps the result; flatMap takes a function that already returns the wrapper and flattens it, so you do not end up with Outcome<Outcome<Int, E>, E>. The same two methods exist on Optional, Array and Result.

Pattern 2: generic collections

A collection written once for every element type is the classic use of generics. A queue is a nice example, because a plain Array is slow at removing from the front. The trick is two stacks: push onto one, pop from the other, and refill when it is empty.

Swift A generic Queue that is also a Sequence

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.

Queue is a struct with value semantics: iterating line works on a copy (the iterator stores its own Queue), so the original keeps its three people afterwards. The array-literal conformance makes var line: Queue = ["Ana", ...] possible. The same pattern, a generic type plus one or two protocol conformances, gives you something that feels built into the language. For a binary heap and a ring buffer built the same way, see Collection Algorithms by Hand.

Pattern 3: protocols with Self requirements

Inside a protocol, Self means "the type that conforms". That lets a protocol say "this method takes another value of the same type" or "this method returns the same type". Equatable and Comparable work this way (static func ==(lhs: Self, rhs: Self)).

Swift Self in a protocol

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.

merged(with:) takes an Inventory when called on an Inventory, and a Tags on a Tags; mixing them is impossible. The array extension is written once, for every Mergeable, and uses the static requirement Element.empty as the starting point of the reduction. That is a common technique: Self-typed requirements let generic code build values of the conforming type.

The price is the one you saw in Opaque and Existential Types: the protocol is awkward as an existential. Two boxes may hold different types, so the compiler refuses to pass one to the other.

Swift Self requirement with existentials (fails on purpose)

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 compiler rejects the call: main.swift:16:21: error: member 'merged' cannot be used on value of type 'any Mergeable'; consider using a generic constraint instead. It is right to refuse, because merging a Count with a Label is meaningless. The fix is to stay generic: take <M: Mergeable> and work with a homogeneous array [M].

Pattern 4: phantom types

A phantom type is a type parameter that does not appear in any stored property. It exists only so the compiler can tell values apart. Think of a distance: a raw Double could be meters or feet, and mixing them is how spacecraft get lost. A phantom Unit parameter makes that a compile-time error at zero runtime cost.

Swift Units as phantom types

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.

Meters and Feet are empty enums that cannot be instantiated: they are only labels. Distance<Meters> and Distance<Feet> are different types, yet each is exactly one Double in memory (the last line prints true). Conversions exist only in the right direction. Now see what the compiler does with a unit mix-up:

Swift Adding meters to feet (fails on purpose)

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 error is main.swift:14:14: error: cannot convert value of type 'Distance<Feet>' to expected argument type 'Distance<Meters>', with a note that the arguments to generic parameter Unit (Feet and Meters) are expected to be equal. The same trick makes typed identifiers: ID<User> and ID<Order> are both wrappers around an Int, but you can never pass an order id where a user id is expected. It costs nothing at run time, and it catches a whole class of mistakes.

Pattern 5: generic higher-order helpers

Generics and closures combine into small reusable tools. A classic one is memoization: wrap a function so each distinct input is computed once.

Swift A generic memoize function

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.

memoize works for any function from a hashable input to any output, and it infers both types from the argument: Int -> Int for slowSquare, String -> String for the closure. The program computes 4 only once (computing 4 appears once), then 5 once, and finishes with hits: 2 misses: 2. The cache is a class so that the returned closure and the caller share one instance. Recursion uses the same idea for speeding up Fibonacci.

Choosing a pattern

Problem Pattern
A value that may be a success or an error, transformed in steps Generic enum with map / flatMap
A container for any element type Generic struct plus Sequence / literal conformances
An operation that combines two values of the same type Protocol with a Self requirement
Preventing values of the same representation being mixed up Phantom type parameter
Reusable behavior around a function Generic function taking @escaping closures

When a generic design gets hard to read, step back and ask whether a concrete type would do. Generics earn their keep when there are, or will be, at least two real uses. Premature abstraction is more expensive than a little duplication.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between map and flatMap on a Result-like type?

    map wraps the transformed value. flatMap expects the transform to produce a wrapper itself, avoiding nested wrappers.
  2. 2. What does Self mean inside a protocol declaration?

    Self is replaced by the conforming type, so func merged(with other: Self) -> Self relates two values of that same type.
  3. 3. What is a phantom type?

    A phantom parameter appears in the type name only. It lets the compiler tell Distance<Meters> from Distance<Feet> with no runtime cost.
  4. 4. Why can't you call items[0].merged(with: items[1]) when items is [any Mergeable]?

    A Self requirement needs both values to be the same type; two existentials give the compiler no such guarantee.
  5. 5. In the memoize example, why is the cache a class?

    A class has reference semantics, so the escaping closure and the returned cache refer to the same storage instead of copies.

Summary

  • A Result-like generic enum carries a success or failure and offers map and flatMap so steps can be chained.
  • Write collections once as generic structs and conform to Sequence and ExpressibleByArrayLiteral to make them feel native.
  • Self requirements let protocols describe operations between values of the same type; keep such protocols for generic code, not any boxes.
  • Phantom types add compile-time safety (units, typed ids) without extra storage.
  • Generic helpers taking closures, like memoize, remove duplicated plumbing.
  • Reach for a pattern when real duplication appears, not before.

Next: Conditional Conformance