Imagine we have this code that works fine for n >= 0 .
func fibonacci(n: Int) -> Int { var memo = [0,1] for var i = 2; i <= n; i++ { memo.append(memo[i-1] + memo[i-2]) } return memo[n] }
If I remove the C-style for the loop due to upcoming changes in Swift 3.0 , I get something like this:
func fibonacci(n: Int) -> Int { var memo = [0,1] for i in 2...n { memo.append(memo[i-1] + memo[i-2]) } return memo[n] }
While this works fine for n >= 2 , this is crashing for numbers 0 and 1 with this error message:
fatal error: it is impossible to form a range with a final <start
What is the most concise way to fix this code so that it works correctly for 0 and 1 ?
(Note: everything is fine, and even desirable, for negative numbers to collapse the application.)
Note: I understand that I can add security instructions:
guard n >= 2 else { return memo[n] }
... but I hope that there is a better way to fix only the faulty part of the code ( 2...n ).
For example, if there was a compressed way to create a range that returns null elements, if end < start , this would be a more ideal solution.
for-loop swift range
Senseful
source share