0

I am trying to use recursion in Swift to print out the Fibonacci sequence for a number "n" iterations. However, I keep getting the same error.

I have already tried doing it without recursion and was able to do it. However, I am now trying to do in a more complex and "computer scientisty" way by using recursion.

func fibonacciSequence (n: Int) -> [Int]  {

// Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.

    var fibonacciArray = [Int]()

    for n in 0 ... n {

        if n == 0 {
            fibonacciArray.append(0)
        }
        else if n == 1 {
            fibonacciArray.append(1)
        }
        else {
            fibonacciArray.append (fibonacciSequence(n: (n - 1)) +
            fibonacciSequence(n: (n-2)))
        }
    }
    return fibonacciArray

I expect to call the function with a number n and for the function to print out the Fibonacci sequence. Example: if n = 5, I expect the console to print 0, 1, 1, 2, 3, 5. The error I get is this: (Cannot convert value of type '[Int]' to expected argument type 'Int').

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • The parameter of the third occurrence of `append` is an array (the return value of to the `fibonacciSequence` method) which causes the error. To implement recursion you have to refactor the code by adding a condition to exit the recursion. Or you could read https://medium.com/swlh/fibonacci-swift-playground-f56d1ff3ea99 – vadian Jun 26 '19 at 17:03
  • @vadian I have already seen the medium link, but was trying to do it as by myself as possible. Thanks for the reply, I will try to refactor the code as you suggest! I got so stuck doing this I was questioning if it could be done using recursion and without the use of a helper. – Alonso Gainza Jun 26 '19 at 17:12

6 Answers6

1

As pointed out above, the return value is causing an error when summed. A possible way (but not recursive) of fixing the code would be to simply change the else statement:

func fibonacciSequence (n: Int) -> [Int]  {

    // Consumes a number "n", which is the number of iterations to go through with the Fibonacci formula and prints such sequence.

    var fibonacciArray = [Int]()

    for n in 0 ... n {

        if n == 0 {
            fibonacciArray.append(0)
        }
        else if n == 1 {
            fibonacciArray.append(1)
        }
        else {
            fibonacciArray.append (fibonacciArray[n-1] + fibonacciArray[n-2] )
        }
    }
    return fibonacciArray
}

A recursive solution would be the following:


func fibonacciSequence (n: Int, sumOne: Int, sumTwo: Int, counter: Int, start: Bool) {

    if start {
        print(0)
        print(1)
    }
    if counter == -1 {
        print(1)
    }
    if (counter == n - 2) {
        return
    }
    let sum = sumOne + sumTwo
    print(sum)

    fibonacciSequence(n: n, sumOne: sumTwo , sumTwo: sum, counter: counter + 1, start: false)
}

fibonacciSequence(n: 8, sumOne: 0, sumTwo: 1, counter: 0, start: true)

There is probably a "nicer" way, but I hope it helps. Cheers.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

These is my solution for fabonacci series in swift 5 playground

func fibonacci(n: Int) {
    var num1 = 0
    var num2 = 1
    var nextNum = Int()
    let i = 1
    var array = [Int]()
    array.append(num1)
    array.append(num2)

    for _ in i...n {
       nextNum = num1 + num2
       num1 = num2
       num2 = nextNum
       array.append(num2)
       print(array)
    }

   print("result = \(num2)")
 }

print(fibonacci(n: 5))

0
    let fibonacci = sequence(state: (0, 1)) {(state: inout (Int, Int)) -> Int? in
        defer { state = (state.1, state.0 + state.1) }
        return state.0
    }
    
    //limit 10
    for number in fibonacci.prefix(10) {
        print(number)
    }
Shenry
  • 11
  • 1
0

// MARK: - Function

func fibonacciSeries(_ num1 : Int,_ num2 : Int,_ term : Int,_ termCount : Int) -> Void{
        if termCount != term{
            print(num1)
            fibonacciSeries(num2, num2+num1, term, termCount + 1)
        }
    }

// MARK: - Calling Of Function fibonacciSeries(0, 1, 5, 0)

// MARK: - out Put 0 1 1 2 3

Note Need to Change only No Of term for fibonacci Series.

0
func fibonacci(n: Int) {
    var seq: [Int] = n == 0 ? [0] : [0, 1]
    var curNum = 2
    while curNum < n{
        seq.append(seq[curNum - 1] + seq[curNum - 2])
        curNum += 1 }
    print(seq) }
-1

Recursive way of fabonacci -> Solutions

func fibo( n: Int) -> Int {

        guard n > 1 else { return n }

        return fibo(n: n-1) + fibo(n: n-2)
}