AnyIterator

struct AnyIterator

A type-erased iterator of Element.

Inheritance IteratorProtocol

This iterator forwards its next() method to an arbitrary underlying iterator having the same Element type, hiding the specifics of the underlying IteratorProtocol.

Initializers

init init(_:) Required

Creates an iterator that wraps a base iterator but whose type depends only on the base iterator's element type.

You can use AnyIterator to hide the type signature of a more complex iterator. For example, the digits() function in the following example creates an iterator over a collection that lazily maps the elements of a Range<Int> instance to strings. Instead of returning an iterator with a type that encapsulates the implementation of the collection, the digits() function first wraps the iterator in an AnyIterator instance.

func digits() -> AnyIterator<String> {
    let lazyStrings = (0..<10).lazy.map { String($0) }
    let iterator:
        LazyMapIterator<IndexingIterator<Range<Int>>, String>
        = lazyStrings.makeIterator()

    return AnyIterator(iterator)
}
  • Parameter base: An iterator to type-erase.

Declaration

@inlinable public init<I>(_ base: I) where Element == I.Element, I: IteratorProtocol
init init(_:) Required

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

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]
  • Parameter body: A closure that returns an optional element. body is executed each time the next() method is called on the resulting iterator.

Declaration

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

Instance Methods

func next() -> Element? Required

Advances to the next element and returns it, or nil if no next element exists.

Once nil has been returned, all subsequent calls return nil.

Declaration

@inlinable public func next() -> Element?