eraseToAnyPublisher

Combine Mid-level Swift 5.1+ iOS 13+ Reviewed By Alok Singh

Pick the fix

Why does func searchResults() -> AnyPublisher<[Item], Never> end with .eraseToAnyPublisher()?

Options
Hint 1 of 1

Look at the type a chain of operators produces.

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

Show answer

Answer: A To hide the long nested operator type so callers depend only on Output and Failure

Correct. The implementation can change without breaking callers.

Why not the others?
  • B To make the publisher run on the main thread. Use receive(on:) for that.
  • C To make the pipeline faster. Erasure adds a small cost; it doesn't speed anything up.
  • D To keep the subscription alive. That is what AnyCancellable does.

30-second answer

Each operator wraps the previous publisher in a new generic type, so a pipeline's real type is long and leaks implementation details. eraseToAnyPublisher() wraps it in AnyPublisher<Output, Failure>, so an API exposes only what it emits and can change its internals freely. Opaque some Publisher also hides the type, but returns one fixed concrete type.

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

Explain type erasure in Combine.

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

  • Nested operator types
  • AnyPublisher at boundaries
  • some Publisher alternative

Deep dive

Erase at module or API boundaries, not between every operator.

Use some Publisher<Output, Failure> (Swift 5.7 primary associated types) when one concrete type is returned.

Erasing has a tiny runtime cost.

Subjects are often exposed through an erased publisher so callers can't send.

Common mistakes

  • Exposing a Subject publicly.
  • Erasing after every operator.

Senior take & follow-ups

Seniors use erasure to design APIs, and know the opaque alternative.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why expose a subject as AnyPublisher?

    Show hint

    Callers can subscribe but not send.

  2. When is some Publisher better?

    Show hint

    When the function always returns the same concrete pipeline.

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