skip to content

In Swift, how do you write a type eraser such as `AnyParser<Output>` by hand, and when does `any Parser<Output>` replace it?

level: seniorimportance: should knowfreq 42%

answer

  1. a concrete type that conforms
  2. generic init with a where clause
  3. forward through closures or a class box
  4. existentials still do not conform

basics

~20 s

A hand-written eraser is a struct, generic over the associated type, that conforms to the protocol and forwards to a captured base. any Parser<Output> usually suffices unless the value must conform, needs extra conformances, or targets below iOS 16.

solid answer

~40 s

Write `struct AnyParser<Output>: Parser` with a generic initializer `init<P: Parser>(_ base: P) where P.Output == Output` that captures what each requirement needs, usually as closures, and forward each requirement through them; the standard library's `AnyIterator` and `AnySequence` use an internal class box instead. Since Swift 5.7, a protocol with a primary associated type can be used as a constrained existential, `any Parser<Int>`, which mixes parser types in one array and still returns `Int?`. That covers most old uses. Keep the eraser when the erased value must conform to `Parser`, for example as the argument of `Pipeline<P: Parser>`, because an existential never conforms to its protocol; when you need extra conformances such as `Sendable`; or when an Apple deployment target is older than the run-time support for parameterized protocol types, such as iOS 16.

code

swift · 30 lines
swift
protocol Parser<Output> {
    associatedtype Output
    func parse(_ input: String) -> Output?
}
struct IntParser: Parser {
    func parse(_ input: String) -> Int? { Int(input) }
}
struct CentsParser: Parser {
    func parse(_ input: String) -> Int? { Double(input).map { Int($0 * 100) } }
}

struct AnyParser<Output>: Parser {
    private let _parse: (String) -> Output?
    init<P: Parser>(_ base: P) where P.Output == Output {
        _parse = base.parse
    }
    func parse(_ input: String) -> Output? { _parse(input) }
}

struct Pipeline<P: Parser> {
    let parser: P
    func run(_ lines: [String]) -> [P.Output] { lines.compactMap(parser.parse) }
}

let pipelines = [AnyParser(IntParser()), AnyParser(CentsParser())]
    .map { Pipeline(parser: $0) }                     // [Pipeline<AnyParser<Int>>]
print(pipelines.map { $0.run(["7", "1.5"]) })         // [[7], [700, 150]]

let boxed: [any Parser<Int>] = [IntParser(), CentsParser()]
print(boxed.map { $0.parse("2") })                    // [Optional(2), Optional(200)]

go deeper

for a junior

Recall that a type eraser like AnyParser wraps any conforming value behind one concrete type, and that the standard library ships erasers such as AnySequence and AnyHashable.

for a middle

Explain the parts of a hand-written eraser: a generic struct over the associated type, a generic init with a where clause, and closures that forward each requirement.

for a senior

Know when any Parser<Output> replaces the eraser and when it cannot: the existential never conforms, so generic type arguments still need the eraser. Mention the iOS 16 run-time requirement.

for a principal

Weigh an eraser's maintenance and call overhead against what it buys, and set a rule that new erasers need a reason any Parser<Output> or a generic helper cannot meet.

## What a type eraser is for A protocol with an associated type, such as `Parser` with its `Output`, describes many concrete types: `IntParser`, `CentsParser` and whatever else conforms. A **type eraser** is an ordinary concrete type whose generic signature keeps only what callers care about, here `AnyParser<Output>`, and hides the rest. The standard library ships several: `AnySequence`, `AnyCollection`, `AnyIterator` and `AnyHashable`. You write your own when your protocol needs one. ## Writing one by hand The usual shape has three parts: 1. **A generic struct over the associated type**, `struct AnyParser<Output>: Parser`. It conforms to the protocol it erases, which is the point of writing it. 2. **A generic initializer** that accepts any conforming base whose associated type matches: `init<P: Parser>(_ base: P) where P.Output == Output`. Inside it, `P` is fully known. 3. **Forwarding storage**: the initializer captures what each requirement needs, most simply as closures (`_parse = base.parse`), and each requirement calls through. For a protocol with many requirements the closures multiply. The standard library uses a **class box** instead: `AnyIterator` stores an internal abstract base class generic over the element, `_AnyIteratorBoxBase<Element>`, and a final subclass generic over the concrete iterator, `_IteratorBox<Base>`, overrides each method to forward to the stored base. One object then carries every requirement. The initializer is the only place where the base's concrete type is still known, so it must capture everything later calls will need. Requirements that return `Self` are the awkward case: the eraser forwards the call and wraps the base's result in a new `AnyParser`, because from the caller's side the erased type is now the eraser itself. ## What `any Parser<Output>` changed Since Swift 5.7 a protocol can declare a **primary associated type**, `protocol Parser<Output>`, and code can then write a **constrained existential**, `any Parser<Int>`. That box knows `Output == Int`, so `parse(_:)` returns `Int?` rather than an erased value, and `[any Parser<Int>]` mixes `IntParser` and `CentsParser` directly. For many past uses of a hand-written `AnyParser`, the existential is now enough: - storing parsers of different types in one array or property; - calling requirements whose signatures use only the constrained associated type; - hiding a factory's concrete parser type. The constraint is what makes this work. A plain `any Parser`, without `<Int>`, still erases the associated type, so its `parse(_:)` returns `Optional<Any>` and the caller has to cast. Declaring primary associated types belongs with the material on associated types; here the question is only which tool erases. ## When the eraser still earns its keep The existential still does **not conform** to its own protocol. `Pipeline(parser: boxed)`, with `struct Pipeline<P: Parser>` and `boxed: any Parser<Int>`, fails with `type 'any Parser<Int>' cannot conform to 'Parser'`. Implicit opening cannot rescue it, because the result type `Pipeline<P>` would expose the opened type. A hand-written eraser is a real conforming type, so `Pipeline<AnyParser<Int>>` is fine. The other reasons to keep one: - **Extra conformances or behaviour.** An eraser can add `Sendable`, logging or caching; an existential cannot gain a conformance. - **Older deployment targets.** Constrained existentials need run-time support that SE-0353 says does not back-deploy. With an iOS 15 deployment target, Swift 6.4 rejects `[any Parser<Int>]` with "runtime support for parameterized protocol types is only available in iOS 16.0.0 or newer". - **A named public type.** A public `AnyParser<Output>` is a type the module owns, documents and can extend. ## What it costs | Cost | Why | |---|---| | Indirect calls | each requirement goes through a stored closure or a class method, which the optimizer usually cannot inline or specialize across | | Allocation | a closure context or class box is typically a heap allocation per erased value | | Maintenance | every requirement is forwarded by hand and must be updated when the protocol grows | Concurrency adds one more rule. Under Swift 6 language mode, an eraser declared `Sendable` must store `@Sendable` closures built from a `Sendable` base: a plain stored closure in a `Sendable` struct is an error in Swift 6 mode and a warning in Swift 5 mode. The general idea of erasing type arguments across languages is covered in the generic programming foundations; the Swift-specific decision is short. Reach for `any Parser<Output>` first, and write `AnyParser` only when something needs a conforming type.

  • Why does the standard library's `AnyIterator` store a class box instead of closures?
    A protocol with several requirements would need one closure per requirement, each with its own capture. `AnyIterator` stores one `_AnyIteratorBoxBase<Element>` reference whose final subclass `_IteratorBox<Base>` holds the concrete iterator and overrides each method to forward to it, so one object and ordinary class dispatch carry every requirement.
  • What must change for `AnyParser` to be `Sendable` in Swift 6 language mode?
    Its stored closure must be `@Sendable`, and the initializer must require `P: Parser & Sendable` so the closure can capture the base safely. A `Sendable` struct storing a plain `(String) -> Output?` closure is an error in Swift 6 mode and a warning in Swift 5 mode.

A hand-written eraser is a universal travel adapter: the wall socket sees one plug shape it accepts, whatever device is behind it. A constrained existential is more like a labelled box of devices: you can use each one, but the box itself does not plug into anything.

  • Since Swift 5.7, any Parser<Int> conforms to Parser, so erasers are obsolete.
  • A type eraser should keep a weak reference to its base to avoid retain cycles.
  • An eraser costs nothing because the optimizer always inlines its stored closures.
  • A type eraser is a protocol extension that hides the associated type.
  • Constrained existentials such as any Parser<Int> back-deploy to every iOS version.

Assumes Swift 6.4: constrained existentials such as any Parser<Int> since Swift 5.7 (run-time support from iOS 16 / macOS 13), and the Sendable eraser rule as an error in Swift 6 language mode, a warning in Swift 5 mode.