Initializer

init(_:)

Creates an iterator that wraps the given closure in its next() method.

Declaration

init(_ body: @escaping () -> Element?)

Parameters

body

A closure that returns an optional element. body is executed each time the next() method is called on the resulting iterator.

Discussion

The following example creates an iterator that counts up from the initial value of an integer x to 15:

var x = 7
let iterator: AnyIterator<Int> = AnyIterator {
    defer { x += 1 }
    return x < 15 ? x : nil
}
let a = Array(iterator)
// a == [7, 8, 9, 10, 11, 12, 13, 14]