Skip to content

Instantly share code, notes, and snippets.

@maysamsh
Last active November 13, 2020 10:37
Show Gist options
  • Save maysamsh/04610316276cf030823a92b589c11901 to your computer and use it in GitHub Desktop.
Save maysamsh/04610316276cf030823a92b589c11901 to your computer and use it in GitHub Desktop.
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