Trying to detect the first run of an Iterator protocol. In the example below I'm trying to start printing Fibonacci series from Zero but it starts from One:
class FibIterator : IteratorProtocol {
var (a, b) = (0, 1)
func next() -> Int? {
(a, b) = (b, a + b)
return a
}
}
let fibs = AnySequence{FibIterator()}
print(Array(fibs.prefix(10)))
What modifications can be made to the above code to detect the first run?
To answer your verbatim question: You can add a boolean variable
firstRunto detect the first call of thenext()method:But there are more elegant solutions for this problem. You can “defer” the update of
aandbto be done after returning the current value:or – perhaps simpler – change the initial values (using the fact that the Fibonacci numbers are defined for negative indices as well):
Note that if you declare conformance to the
Sequenceprotocol then you don't need theAnySequencewrapper (there is a default implementation ofmakeIterator()for types conforming toIteratorProtocol). Also value types are generally preferred, so – unless the reference semantics is needed – you can make it astruct: