Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Created December 14, 2015 21:31
Show Gist options
  • Select an option

  • Save hsavit1/3a25879147b6a5b86fbd to your computer and use it in GitHub Desktop.

Select an option

Save hsavit1/3a25879147b6a5b86fbd to your computer and use it in GitHub Desktop.
Fibonacci sequence in Swift
/// Generator for Fibonacci sequence
func fibonacciGenerator() -> AnyGenerator<Int> {
var a = -1
var b = 1
return anyGenerator {
let next = a + b
a = b
b = next
return next
}
}
/// Infinite lazy sequence of Fibonacci numbers
let fibs = AnySequence(fibonacciGenerator)
// Print first 20 elements
for n in fibs.prefix(20) { print(n) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment