Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A FibonacciSequence type
import Foundation
struct FibsIterator: IteratorProtocol {
private var state:(UInt, UInt) = (0, 1)
private var upTo: Int
private var counter = 0
init(upTo: Int) {
self.upTo = upTo
}
mutating func next() -> UInt? {
guard upTo > counter else {return nil}
guard upTo > 0 else {return nil}
let upcomingNumber = state.0
state = (state.1, state.0 + state.1)
counter += 1
return upcomingNumber
}
}
struct FibsSequence: Sequence {
private var upTo: Int
init(upTo: Int) {
self.upTo = upTo
}
func makeIterator() -> FibsIterator {
return FibsIterator(upTo: upTo)
}
}
for (index, fib) in FibsSequence(upTo: 60).enumerated() {
print("fib: \(fib), index: \(index + 1)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.