Previously I was using the following function to make my custom class conform to the SequenceType protocol:
func generate() -> AnyGenerator<UInt32> {
var nextIndex = 0
return anyGenerator {
if (nextIndex > self.scalarArray.count-1) {
return nil
}
return self.scalarArray[nextIndex++]
}
}
This is a similar implementation to the accepted answers to these two questions:
- Add "for in" support to iterate over Swift custom classes
- Add 'for...in' support to a class in Swift 2
But after a Swift 2.2 update...
'++' is deprecated: it will be removed in Swift 3
func generate() -> AnyGenerator<UInt32> {
var nextIndex = 0
return AnyGenerator {
if (nextIndex > self.scalarArray.count-1) {
return nil
}
nextIndex += 1
return self.scalarArray[nextIndex]
}
}
But this throws an Index out of range error because I actually need to use the pre-incremented index and then increment it after the return.
How does this work for AnyGenerator now in Swift? (Also, should I be decrementing rather than incrementing as the other two answers I linked to do?)