0Pricing
Swift Academy · Lesson

Type erasure patterns (AnySequence/AnyIterator)

Use AnySequence and AnyIterator to erase concrete sequence/iterator types so APIs can return “a sequence of T” without exposing implementation.

Why type erasure?

Type erasure hides concrete types behind a stable wrapper. With AnySequence / AnyIterator you can return “a sequence of elements” without exposing internal structure.

The limitation

Sequence has an associated type (Element), so the bare protocol cannot be used as a concrete value type. We need a wrapper.

// Goal: return "some Sequence<Int>"
// This won't compile as a stored value type:
// let s: Sequence = [1,2,3]   // Protocol with associated types
// Instead, erase the type to AnySequence<Int>.

All lessons in this course

  1. associatedtype & generic protocols
  2. Type erasure patterns (AnySequence/AnyIterator)
  3. When to use existentials (any P) vs generics
← Back to Swift Academy