0Pricing
Swift Academy · Lesson

Lazy map and filter

Chain lazy transforms without intermediate arrays.

Intermediate Arrays

Eager chains allocate a fresh array between every step. filter().map() on a big array builds two full arrays even though you may want only a few elements.

The Eager Allocation

Two intermediate arrays are created here:

let nums = Array(1...6)
let result = nums
    .filter { $0 % 2 == 0 }  // builds [2, 4, 6]
    .map { $0 * 10 }         // builds [20, 40, 60]
print(result)  // [20, 40, 60]

All lessons in this course

  1. The lazy Property
  2. Lazy map and filter
  3. Lazy vs Eager Trade-offs
  4. Building Custom Lazy Sequences
← Back to Swift Academy