Here's a function that takes an input n
and returns an array of the first n
Fibonacci numbers in Swift:
main.swift382 chars18 lines
The function first checks to make sure that n
is greater than 0. If it is not, it returns an empty array. If n
is 1, it returns an array containing only 0. If n
is 2, it returns an array containing [0, 1] (these are the first two Fibonacci numbers).
If n
is greater than 2, the function uses a for
loop to iterate from 2 up to n
, and calculates each Fibonacci number by adding together the previous two numbers in the result
array. Each new Fibonacci number is added to the result
array using the append
method. Finally, the result
array is returned.
gistlibby LogSnag