← All languages
Swift function of the day
Random

sequence

Return a sequence of repeated applications of a closure to an initial value.

Description

The sequence(first:next:) function returns an infinite sequence starting with the given first value and applying the next closure to produce subsequent elements. The sequence terminates when the closure returns nil.

There is also sequence(state:next:) which maintains mutable state across iterations, useful for more complex sequence generation.

sequence is useful for generating linked list traversals, tree paths, or any iterative computation that can be expressed as repeated function application.

Arguments

NameDescriptionOptional
first The first element of the sequence. No
next A closure that returns the next element, or nil to end. No

Example

let powers = sequence(first: 1) { $0 * 2 }
let first10 = Array(powers.prefix(10))
print(first10)  // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Reference