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.

Lesson 2 of 38 steps

Type erasure patterns (AnySequence/AnyIterator) is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 3 lessons in total.

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>.

AnySequence wrapper

AnySequence wraps any concrete sequence (Array, Set, custom) and exposes a uniform type like AnySequence<Int>.

// Build an AnySequence<Int> from an Array
let a = [1, 2, 3]
let seq1: AnySequence<Int> = AnySequence(a)
// Consume like any sequence
for x in seq1 { print(x, terminator: " ") }
print("")

AnyIterator wrapper

AnyIterator wraps a closure that produces elements. Wrap it in AnySequence to expose a full sequence.

// Create an AnyIterator<Int> by hand
var i = 0
let it = AnyIterator<Int> {
    // Return next number or nil to stop
    guard i < 3 else { return nil }
    defer { i += 1 }
    return i
}
let seq2 = AnySequence(it)
for x in seq2 { print(x, terminator: " ") }  // 0 1 2
print("")

Uniform return type

Type erasure lets one function return different implementations under a single stable return type (AnySequence<Int>).

// Return a sequence of Int without exposing concrete type
func numbers(flag: Bool) -> AnySequence<Int> {
    if flag {
        // Array-based
        return AnySequence([10, 20, 30])
    } else {
        // Lazy generated with AnyIterator
        var n = 1
        let it = AnyIterator<Int> {
            guard n <= 3 else { return nil }
            defer { n += 1 }
            return n * 100
        }
        return AnySequence(it)
    }
}

for x in numbers(flag: true)  { print(x, terminator: " ") }  // 10 20 30
print("")
for x in numbers(flag: false) { print(x, terminator: " ") }  // 100 200 300
print("")

When to use it

Use type erasure when:

  • You want to hide implementation details of sequences/iterators.
  • APIs must return the same type regardless of internal branches.
  • Generics become too exposed at API boundaries.

Notes: prefer generics for performance and clarity inside modules; use AnySequence/AnyIterator at boundaries when needed.

AnySequence purpose

Quick check: What does AnySequence<T> buy you?

Recap

Recap: Wrap concrete sequences/iterators with AnySequence / AnyIterator to erase types and return “a sequence of T” from flexible APIs.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Type erasure patterns (AnySequence/AnyIterator)” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Type erasure patterns (AnySequence/AnyIterator)”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 3 lessons in total.

What will I learn in “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. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 3.

How long does the “Type erasure patterns (AnySequence/AnyIterator)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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