jweinst1
7/31/2016 - 10:02 PM

lazycollection.swift

//protocol for lazy collections
protocol Lazy {
    associatedtype T
    var canIterate:Bool {get set}
    func next() -> T
}


class GenericLazyIterator<T>:Lazy {
    var canIterate: Bool
    let collection:[T]
    var iterMarker:Int
    
    init(collection:[T]) {
        self.collection = collection
        self.canIterate = true
        self.iterMarker = 0
    }
    
    func next() -> T? {
        if self.canIterate {
            let nextitem = self.collection[self.iterMarker]
            self.iterMarker += 1
            guard self.iterMarker < self.collection.count else {
                self.canIterate = false
            }
            return nextitem
        }
        else {
            return nil
        }
    }
}