Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Playground contents showing the use of AnyIterator<T>
import Foundation
class ListOfIntegers: Sequence {
typealias Element = Int
private var backingStore = [Int]()
init() {}
init(_ value: [Int]) {
self.backingStore = value
func makeIterator() -> AnyIterator<Int> {
// We establish the index *outside* the
// closure. More below.
var index = self.backingStore.startIndex
// Note the use of AnyIterator.init(:) with
// trailing closure syntax.
return AnyIterator { () -> Int? in
// Is the current index before the end?
if index < self.backingStore.endIndex {
// If so, get the current value
let currentValue = self.backingStore[index]
// Set a new index for the next execution
index = self.backingStore.index(after: index)
// Return the current value
return currentValue
} else {
// We've run off the end of the array, return nil.
return nil
let list = ListOfIntegers([1, 2, 3, 4, 5])
let iterator = list.makeIterator()
while let i = {

This comment has been minimized.

Copy link

@t089 t089 commented Dec 19, 2019

Yeah that is a nice application of AnyIterator! This particular implementation might be considered dangerous because your iterator iterates over the backing store effectively by reference since it captures a reference to the enclosing class. Maybe this is exactly what you want, just good to be aware of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment