Created
January 19, 2016 19:25
-
-
Save cellularmitosis/64d4a2d2d6dfa33916fc to your computer and use it in GitHub Desktop.
Alternate take on the sequence protocol using AnyGenerator. See http://stackoverflow.com/a/26219833/558735
This file contains hidden or 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
// paste this into a playground | |
import Foundation | |
class Car { | |
var name : String | |
init(name : String) { | |
self.name = name | |
} | |
} | |
class Cars : SequenceType { | |
var carList = [Car]() | |
func generate() -> AnyGenerator<Car> { | |
// keep the index of the next car in the iteration | |
var nextIndex = 0 | |
// Construct a AnyGenerator<Car> instance, passing a closure that returns the next car in the iteration | |
return anyGenerator({ [weak self] in | |
guard let car = self?.carList.get(nextIndex) else | |
{ | |
return nil | |
} | |
nextIndex += 1 | |
return car | |
}) | |
} | |
} | |
extension Array | |
{ | |
func get(index: Int) -> Element? { | |
guard index >= 0 && index < self.count else { | |
return nil | |
} | |
return self[index] | |
} | |
} | |
let cars = Cars() | |
cars.carList.append(Car(name: "Honda")) | |
cars.carList.append(Car(name: "Toyota")) | |
for car in cars { | |
debugPrint(car.name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment