Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created October 20, 2017 12:08
Show Gist options
  • Save shaps80/3d770fe9233bb5c1bec834f9f671905f to your computer and use it in GitHub Desktop.
Save shaps80/3d770fe9233bb5c1bec834f9f671905f to your computer and use it in GitHub Desktop.
An iterator that automatically wraps back to the `firstIndex` after the `endIndex` is reached.
import Foundation
public struct InfiniteIterator<Base: Collection>: IteratorProtocol {
private let collection: Base
private var index: Base.Index
public init(collection: Base) {
self.collection = collection
self.index = collection.startIndex
}
public mutating func next() -> Base.Iterator.Element? {
guard !collection.isEmpty else {
return nil
}
let result = collection[index]
collection.formIndex(after: &index)
if index == collection.endIndex {
index = collection.startIndex
}
return result
}
}
let letters = ["a", "b", "c"]
var iterator = InfiniteIterator(collection: letters)
iterator.next() // a
iterator.next() // b
iterator.next() // c
iterator.next() // a
iterator.next() // b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment