define a function called what that gives the nth fibonacci number in swift

Here's the solution using recursion:

main.swift
func fibonacci(_ nth: Int) -> Int {
    if nth <= 1 {
        return nth
    } else {
        return fibonacci(nth - 1) + fibonacci(nth - 2)
    }
}

// example usage
fibonacci(6) // returns 8
193 chars
11 lines

This function takes an integer nth as input and returns the corresponding Fibonacci number. It uses recursion to calculate the nth Fibonacci number by summing the previous two (n-1 and n-2) Fibonacci numbers. The base case is when nth <= 1, which returns nth itself since the Fibonacci sequence starts with 0 and 1.

gistlibby LogSnag