Last active
November 13, 2020 10:37
-
-
Save maysamsh/04610316276cf030823a92b589c11901 to your computer and use it in GitHub Desktop.
A FibonacciSequence type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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