find the nth fibonacci number in swift

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.swift
func fibonacci(_ n: Int) -> Int {
    if n <= 1 {
        return n
    }
    return fibonacci(n - 1) + fibonacci(n - 2)
}

let n = 7 // the nth Fibonacci number we want to find
let result = fibonacci(n)
print("The \(n)th Fibonacci number is: \(result)") // prints "The 7th Fibonacci number is: 13"
298 chars
11 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