Created
December 18, 2019 14:35
-
-
Save cliss/49af0498648566e8c1dde8a5aac9e677 to your computer and use it in GitHub Desktop.
Playground contents showing the use of AnyIterator<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.