The following Q&A covers a few methods of generating Fibonacci numbers in Swift, but it's quite outdated (Swift 1.2?):
Question: How could we generate Fibonacci numbers neatly using modern Swift (Swift >= 3)? Preferably methods avoiding explicit recursion.
Details
XCode Version 10.0 beta 6, Swift 4.2
The control flow is required to get either the first or the first two iterations of the fibonacci seq starting with 0.
Time Complexity: O(n)
Space Complexity: O(n)
Code
Usage
fib(8)
//print(fib(8))
This is bad to use recursion!! recursion is evil!
I would have rather done it this way:
Which is much faster and cleaner!
An alternative for Swift 3.0 would be to use the helper function
from Express for loops in swift with dynamic range:
Note that in order to include zero in the resulting sequence, it suffices to replace the initial value
(0, 1)
by(1, 0)
:That makes the "artificial" check
redundant. The underlying reason is that the Fibonacci numbers can be generalized to negative indices (https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):
Details
Xcode 9.3.1, Swift 4.1
Solution
Usage
Results
In Swift 3.1, here's an iterator that generates Fibonacci numbers forever, and an infinite sequence derived from it:
To print the first 10 Fibonacci numbers:
If you want to filter or map this infinite sequence you'll need to call
.lazy
first, since otherwise filter or map will behave strictly and will not terminate. Here are the first 5 even Fibonacci numbers:Using the global
sequence(state:next:)
functionSwift 3.0
As one alternative we could make use of one the neat global
sequence
functions, a pair of functions that were implemented in Swift 3.0 (as described in evolution proposal SE-0094).sequence(first:next:)
sequence(state:next:)
Using the latter of these, we may keep the previous and current state of the Fibonacci numbers sequence as the mutable
state
property in thenext
closure ofsequence(state:next:)
.Or, condensing this using tuple hacks (however executing
next
one extra, unnecessary, time)Note that we explicitly terminate the sequences with a
nil
return when the... <= through
condition is no longer met.Example usage:
We could also remove the termination criteria from above to construct an infinite sequence of fibonacci numbers, to be used in combination e.g. with
prefix
:Swift 3.1
When Swift 3.1 arrives, the
prefix(while:)
method for sequences, as described in evolution proposal SE-0045, will have been implemented. Using this additional feature, we can modify thefibs
methods above to avoid the explicit by-nil
conditional sequence termination:Examples should work the same as for Swift 3.0 above.