Search code examples
arraysfunctionswift2return-valueswift-playground

Executing bad excess on receiving a function return array?


What is the problem with the following function to receive and execute:

 func FibFast(num: Int) -> Array<Int> {
        var fib_arr = [Int](num)
        if num < 1 {
            fib_arr[0] = 0
            return fib_arr
        } else if num < 2 {
            fib_arr[1] = 1
            return fib_arr
        }else {
            for var i = 2; i < num; i++ {
                fib_arr[i] = fib_arr[i-1] + fib_arr[i-2]
            }
            return fib_arr
        }
    }

when I am trying to receive the array like:

var newArray = FibFast(10)

it's producing a bad execution.


Solution

  • You are attempting to subscript the array with indexes that don't exist, similarly in your else case you are trying to subscript to an index of 2 when the array is empty.

    the line var fib_arr = [Int]() creates an empty array on integers. when you use fib_arr[0] = 0 you are trying to assign the value at index 0 to have a value of 0 but no value currently exists. I would recommend using the append(_) method ie. fib_arr.append(0).

    Also when you pass in a value of 10 or anything that is 2 or more as the num parameter your if-else if-else statement is executing the for loop where you are attempting to access the index of 0 and 1 which have not been set as the earlier statements were never executed as they were skipped by the if-else if-else block.

    The for loop and assign the values with subscripts is very indicative of the fact that you've probably learnt a different language before swift. You should note that the classic c-style for loop you are trying to use will be removed from swift soon so its better to get in the habbit of no using it. Ive rewritten your code as close to the way you wrote yours, please don't hesitate to ask if you have any questions about it.

    func fib(num: Int) -> [Int] {
      var fib_arr = [Int]()
      if num == 0 {
        fib_arr.append(0)
      } else if num == 1 {
        fib_arr.append(0)
        fib_arr.append(1)
      } else {
        fib_arr = [0, 1]
        for i in 2..<num {
          fib_arr.append(fib_arr[i - 1] + fib_arr[i - 2])
        }
      }
      return fib_arr
    }