This question has already been answered for earlier versions of Swift, but I'm wondering how to add 'for...in' support to a class in Swift 2. It appears that enough has changed in the new version of Swift to make the answer significantly different. For example, it appears that you should be using the AnyGenerator protocol now?
There are just two changes:
GeneratorOf
is now called AnyGenerator
.
GeneratorOf.init(next:)
is now a function anyGenerator()
That gives us:
class Cars : SequenceType {
var carList : [Car] = []
func generate() -> AnyGenerator<Car> {
// keep the index of the next car in the iteration
var nextIndex = carList.count-1
// Construct a GeneratorOf<Car> instance, passing a closure that returns the next car in the iteration
return anyGenerator {
if (nextIndex < 0) {
return nil
}
return self.carList[nextIndex--]
}
}
}
(I've edited the linked answer to match Swift 2 syntax.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With