5.2. While loops

The second most common loops in Swift are while loops. We use a while loop to run a code block repeatedly as long as a given condition is true. A general structure of a while loop is:

while condition {
    //code block
}

For example, the following code prints all the integers below 50:

var targetNum = 1
while targetNum <= 50{
    //code block
    print(targetNum)
    targetNum += 1
}

Here the condition is: if targetNum is less than or equal to 50.

Last updated

Was this helpful?