To find the nth Fibonacci number in Swift, we can use recursion, which involves breaking down the problem into smaller subproblems until we reach the base case, which for this problem is when n equals 0 or 1.
Here is the Swift code to find the nth Fibonacci number using recursion:
main.swift298 chars11 lines
In this code, we define a function called fibonacci
that takes an integer n
as its input and returns an integer as its output. If n
is less than or equal to 1, we simply return n
. Otherwise, we compute the nth Fibonacci number by recursively calling the fibonacci
function with the parameters n - 1
and n - 2
, and adding the results of those two function calls together.
To use this function, we simply call it with the value of n
that we want to find, and it will return the nth Fibonacci number. In this example, we set n
to 7 and print the result, which should be 13.
gistlibby LogSnag