Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Last active November 29, 2017 01:08
Show Gist options
  • Save cjnevin/d548748c0de58de7a904a50c914e9434 to your computer and use it in GitHub Desktop.
Save cjnevin/d548748c0de58de7a904a50c914e9434 to your computer and use it in GitHub Desktop.
//
// LoopingIterator.swift
//
// Created by Chris Nevin on 01/11/2016.
// Copyright © 2016 CJNevin. All rights reserved.
//
import Foundation
public struct LoopingIterator<Base: Collection> : IteratorProtocol {
private let collection: Base
public var index: Base.Index
public var endIndex: Base.Index
public var current: Base.Iterator.Element? {
if (collection.startIndex...collection.endIndex).contains(index) {
return collection[index]
} else {
return nil
}
}
public init(collection: Base) {
self.collection = collection
self.index = collection.startIndex
self.endIndex = collection.endIndex
}
@discardableResult 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
}
}
public extension Array {
public func makeLoopingIterator() -> LoopingIterator<Array> {
return LoopingIterator(collection: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment