Here is my code for counting Fibonacci number, and when I compile it, here is an error "Index out of range".
func fib(n: Int) -> Int {
var fibArray = [Int]()
fibArray.insert(0, at: 0)
fibArray.insert(1, at: 1)
for i in 2...n {
fibArray[i] = fibArray[i-1] fibArray[i-2]
}
return fibArray[n]
}
var a = fib(n: 8)
print(a)
CodePudding user response:
You were doing nicely with items 0 and 1, so might as well keep the same logic in your loop.
fibArray.insert(fibArray[i-1] fibArray[i-2], at: i)