Challenge C: Recursive functions
In this challenge, you’re going to see what happens when a function calls itself, a behavior called recursion. This may sound unusual, but it can be quite useful.
You’re going to write a function that computes a value from the Fibonacci sequence. Any value in the sequence is the sum of the previous two values. The sequence is defined such that the first two values equal 1. That is, fibonacci(1) = 1 and fibonacci(2) = 1.
Write your function using the following declaration:
func fibonacci(_ number: Int) -> Int
Then, verify you’ve written the function correctly by executing it with the following numbers:
fibonacci(1) // = 1 fibonacci(2) // = 1 fibonacci(3) // = 2 fibonacci(4) // = 3 fibonacci(5) // = 5 fibonacci(10) // = 55
Hint 1: For values of number less than 0, you should return 0.
Hint 2: To start the sequence, hard-code a return value of 1 when number equals 1 or 2.
Hint 3: For any other value, you’ll need to return the sum of calling fibonacci with
number - 1 and number - 2.
All the variables and constants you’ve dealt with so far have had concrete values. When you had a string variable, like var name, it had a string value associated with it, like "Matt Galloway". It could have been an empty string, like "", but nevertheless, there was a value to which you could refer.
That’s one of the built-in safety features of Swift: If the type says Int or String, then there’s an actual integer or string there, guaranteed.
This chapter will introduce you to the concept of optionals, a special Swift type that can represent not just a value, but also the absence of a value. By the end of this chapter, you’ll know why you need optionals and how to use them safely.