Last active
November 29, 2017 01:08
-
-
Save cjnevin/d548748c0de58de7a904a50c914e9434 to your computer and use it in GitHub Desktop.
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
// | |
// 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