iOS Swift Collections and Control Flow Control Flow With Loops While and Repeat While

How exactly does this while loop work?

it says:

"var index = 1

while index < { print("random sentence") index += 1 }"

I'm mostly confused about what "+=" does and how it will only print the array and not the string.

1 Answer

Alex Koumparos
Alex Koumparos
Python Web Development Techdegree Student 35,893 Points

Hi Brendan,

First, there is a small typo in your example code: you haven't included a value for the index to be compared to. For illustration I've used the value 3.

Here is the corrected while loop:

var index = 1
while index < 3 {
    print("random sentence")
    index += 1

This code will print "random sentence" twice. It won't print an array (as there isn't one in this code snippet).

The index += 1 is a shortcut for writing: index = index + 1. Any time you see a mathematical operator (+,-.*,/) immediately followed by the assignment operator (=), it means "take the value in the variable to the left of the operator, apply the math operator with the value to the right, then put that new value back in the variable".

In the while loop above, the variable index starts with the value of 1. Then we go into the loop (because 1 is less than 3), we print the string, then index gets increased by 1. Since 2 is still less than 3, we go back into the loop and print the string again. Again, index gets increased by 1. It is now no longer less than 3, so the loop exits.

Hope that clears things up.