0Pricing
Swift Academy · Lesson

Ranges as Collections

Map and filter over range sequences.

Ranges Are Sequences

A range is more than a span of numbers; it is a sequence you can transform with collection methods like map and filter.

let squares = (1...5).map { $0 * $0 }
print(squares)

Mapping a Range

(1...n).map { ... } turns each number into a new value, producing an array. Note the parentheses around the range.

let doubled = (1...4).map { $0 * 2 }
print(doubled)

All lessons in this course

  1. Closed and Half-Open Ranges
  2. One-Sided Ranges
  3. Counting with stride(from:to:by:)
  4. Ranges as Collections
← Back to Swift Academy