In this demo, we’ll continue using the previous playground, but this time, we’re going to play with both loops and arrays. You saw the while loop. Let’s put this in practice. Add the following:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
print(sum)
Here we set the sum variable to 1. The while loop will run so long as the sum variable is less than 1000. For ever iteration, the sum variable is added to itself with one added. After the first iteration, the sum variable will equal to 3. In the second iteration, the value equals 7.
Run your code, and you get 1023. How many loop iterations occurred? Add the following:
var sum = 1
var iterations = 0
while sum < 1000 {
sum = sum + (sum + 1)
iterations = iterations + 1
}
print(sum)
print(iterations)
Believe it or not, the loop only ran nine times!
A for-in loop is great for looping through a range of values. This loop goes through a range and stores the values in a temporary variable. Add the following:
for i in 1...3 {
print(i)
}
Okay, a few things are happening here. This loop starts with the for keyword followed by a variable. After the i variable is the in keyword. The last bit is a range from one to three. As the loop iterates through that range, the value is set to i. This kind of loop works well with arrays. Before we play with loops and arrays, you need to make arrays.
Let’s create an animal array.
var animals = [ "🐕", "🐁", "🐄" ]
This is an emoji array. This array can either be typed as a string array or a character array. It’s hard to tell which. Underneath the definition, type the variable name. You’ll see it listed as a string array.
Remove that name, update the variable to the following:
var animals: [String] = [ "🐕", "🐁", "🐄" ]
This makes it clear you are working with a String array. Notice the array type is between brackets. That indicates an array. Now in some languages, you can add whatever you want to an array. With Swift, you need to use the correct type. For example, you add things with the append method. Try adding a number:
animals.append(1)
In Swift, arrays must use be of the same type. This means a string array can only contain strings. An integer array can only contain integers. This prevents common bugs. For example, in a mixed array, you may accidentally try to uppercase an integer. So in this case, we can update the code to the following:
animals.append("🐓")
And the error goes away. Arrays are often accessed by index. Since arrays are zero based, to get the first element, you’d write something like this:
animals[0]
But since arrays are objects, you can use properties and methods on them. Here’s another way to get the first element.
animals.first
And here’s how to get the last element:
animals.last
To see the length of the array, you use the count property. This tells you the amount of elements.
animals.count
You see we have four elements. As mentioned, loops and arrays work really well together. Here’s how to print out all the elements in the array.
for i in 0...animals.count {
print(animals[i])
}
This array loops through all the elements based on the size of the array. The index is fetched based on the current iteration. But there is a problem. Run the code. You’ll see an Index out of range error. You are trying to access an element in the array that doesn’t exist. Select all the code before the array. Now, press command-forward slash. This comments out all the previous code. If you want to uncomment it, just press command-forward slash again. Keep the code commented out. Click the bottom speedometer icon and select the Step Through My Code option. Now run your code. Watch it loop through each iteration.
You can see after it completes the final emoji, it loops one more time. That’s due to the range. Update it to the following:
for i in 0...animals.count - 1 {
print(animals[i])
}
Now click the speedometer icon and select the Run My Code option. Now run and everything runs fine. There’s one last loop that can help you out. When working with an array, you can just use a regular for loop. Most of the times, you’ll want to use this loop when working with arrays.
for animal in animals {
print(animal)
}
That’s much easier and thankfully, there is no worry about an index out of range error.