In this demo, you’ll improve the code you wrote last lesson for the Fibonacci sequence to use loops.
Open Xcode on your Mac and create a new playground.
You’ll write the Swift code to generate the first 11 numbers in the sequence, from index zero to 10.
Remove the existing code from your playground and define a variable for the array:
var fibonacciSeries: [Int] = []
Next, you need to create the loop. You have two options for that:
-
Use a
whileloop and increment the index yourself. -
Create a
forloop that goes from zero to 10.
The first looks easy enough, but you’ll need to increment the value of the index yourself and write the condition index <= 10. I prefer using for loops whenever I know in advance that the loop has a set number of repetitions/iterations.
for loops iterate over elements in an array (or a sequence) one by one. Swift allows you to define a sequence using a nice form, called ranges. Add this code after the array variable:
for index in 0...10 {
}
0...10 is a range that starts with the first number on the left, and ends with the number on the right, including it. If you want to create a range that excludes the number on the right, you’d write it like this: 0..<10.
Now, you can start to calculate the sequence itself. If you remember, the sequence starts with 0, then 1, and progresses so on from there as the sum of the previous two digits. So only the first two numbers are pre-defined. Let’s translate that into Swift. Write this inside the for loop code block:
if index == 0 {
fibonacciSeries.append(0)
} else if index == 1 {
fibonacciSeries.append(1)
}
Now that you have the first two indices covered, write the code to calculate the rest of the sequence:
else {
let element1 = fibonacciSeries[fibonacciSeries.count-1]
let element2 = fibonacciSeries[fibonacciSeries.count-2]
fibonacciSeries.append(element1 + element2)
}
At the very end, after the last curly bracket, print the whole array to see the sequence printed in the console:
print(fibonacciSeries)
Run the playground to see the results in the bottom pane of the Xcode window.
Before you finish, you can make a few improvements to the code to make it more readable. Notice that the if conditions for the first two elements are almost identical, and that the value you’re adding to the array equals the value of the index itself.
Change those two conditions into one:
if index < 2 {
fibonacciSeries.append(index)
}
Run the playground again to ensure the result is identical to before and that nothing broke.
With the last change, the code becomes simpler to read and more straightforward.
In the next part of this lesson, you’ll learn about functions and how they make your code more organized and easier to understand.