Skip to content

Instantly share code, notes, and snippets.

@cliss
Created December 18, 2019 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliss/49af0498648566e8c1dde8a5aac9e677 to your computer and use it in GitHub Desktop.
Save cliss/49af0498648566e8c1dde8a5aac9e677 to your computer and use it in GitHub Desktop.
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 = iterator.next() {
print(i)
}
@t089
Copy link

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