Iterator


My notes on an async iterator class. This iterator class can be used for iterating simple arrays, or handle async local/remote services. Here is an example where the iterator is used to iterate a simulated remote service.

/**
 * Demonstrates async iterator
 */
class DemoIterator:ArrayIterator<DemoItem> {
    var complete:()->Void
    init(array: Array<T>,onComplete:@escaping ()->Void) {
        self.complete = onComplete
        super.init(array: array)
    }
    func iterate(callBack:@escaping (_ item:DemoItem, _ success:Bool)->Void){
        if hasNext() {
            let item:DemoItem = next()
            DispatchQueue.global(qos: .background).async {
               sleep(Int(2.6).uint32)/*Simulates some remote service taking 2.6sec*/
               let eitherOr:Bool = arc4random_uniform(2) == 0/*heads or tails*/
               callBack(item,eitherOr)
            }
        }else{
            complete()
        }
    }
}
struct DemoItem{}
/**
 * Example use:
 */
var validItems:[DemoItem] = []
var arrIterator:DemoIterator = DemoIterator(array:[DemoItem(),DemoItem(),DemoItem()]){
   print("All done: \(validItems.count)")//between 0 and 3
}
func iterate(){
    arrIterator.iterate{ item,success in
        if success {
            validItems.append(item)
        } else {
            iterate()
        }
    }
}
//iterate()

Supporting files:

After the jump, hit the keyboard char T and search for Iteratable.swift

https://github.com/eonist/swift-utils