Created
October 20, 2017 12:08
-
-
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.
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 | |
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