Loops & Arrays
Computers are great for doing repeated tasks. Computers process information at unimaginable speeds. A task that would take hundreds of hours by a single person can take seconds by a machine. These repeated tasks are called loops and they are built right into the language.
There are many different types of loops in Swift that all do similar things. For this course, you’ll learn about three of them: the while loop, the for loop, and the for-in loop. Here’s an example of a while loop:
var sum = 0
while sum < 1 {
sum = sum + (sum + 1)
}
All these require two things: an exit condition and some code to run. Here is the breakdown:
-
An exit condition determines the completion of a loop. Some loops manage this in the background whereas other loops require you to write the condition with boolean logic like if statements. Should you make a mistake with the exit condition, you may enter an infinite loop. When this happens (and it happens to every developer), you’ll need to stop the program or wait until the heat death of the universe (a long time). In the case of the while loop, the code will continue to loop until the sum variable is one or more.
-
The code you need to run is put between curly braces. The loop processes the code between the curly braces for each iteration. Any variables declared in the curly braces are lost with each iteration. If you need variables to persist between iteration, you need to declare those variables outside of the loop.
There are some loops that require the developer to track each loop iteration. Like the exit condition, if you mess up tracking the iteration, you’ll be stuck in an infinite loop.
Working with Collections
A collection is a large assortment of data. Whereas a variable can only hold one type of value, a collection can hold as many values as you want. Swift has lots of different collection types, but the array is the most fundamental collection. Here is an example of an array:
var players = ["Dana", "Jeremy", "Keith", "Mark"]
This is a string array. The contents of the array are contained within square brackets. It also contains a number of different names with each name separated by a comma. Looking at this array, each name is considered an element. Each element exists at an index. This is where things get weird. Computers count by zero. This mean Dana, who is the first element, is located at the zero index. Jeremy is the first index. Keith is the second index. Finally, Mark is the third index.
This is important when accessing the index. For example:
print(players[0]) // Dana
This code prints the first element on the screen. A common mistake is to access an index outside the bounds of the array. For example:
print(players[4]) // Error
This will cause your program to crash. You are exceeding the bounds of the array. Thankfully, there is a count property to let you know the actual size.