Continue and labeled statements

Sometimes you’d like to skip a loop iteration for a particular case without breaking out of the loop entirely. You can do this with the continue statement, which immediately ends the current iteration of the loop and starts the next iteration.

Note: In many cases, you can use the simpler where clause you just learned about. The continue statement gives you a higher level of control, letting you decide where and when you want to skip an iteration.

Take the example of an 8 by 8 grid, where each cell holds a value of the row multiplied by the column:

It looks much line a multiplication table, doesn’t it?

Let’s say you wanted to calculate the sum of all cells but exclude all even rows, as shown below:

Using a for loop, you can achieve this as follows:

var sum = 0

for row in 0..<8 { if row % 2 == 0 {

continue

}

for column in 0..<8 { sum += row * column

}

}

When the row modulo 2 equals 0, the row is even. In this case, continue makes the

for loop skip to the next row.

Just like break, continue works with both for loops and while loops.

The second code example will calculate the sum of all cells, excluding those where the column is greater than or equal to the row.

To illustrate, it should sum the following cells:

Using a for loop, you can achieve this as follows:

var sum = 0

rowLoop: for row in 0..<8 { columnLoop: for column in 0..<8 {

if row == column { continue rowLoop

}

sum += row * column

}

}

This last code block makes use of labeled statements, labeling the two loops as rowLoop and the columnLoop, respectively. When the row equals the column inside the inner columnLoop, the outer rowLoop will continue.

You can use labeled statements like these with break to break out of a certain loop. Normally, break and continue work on the innermost loop, so you need to use labeled statements if you want to manipulate an outer loop.

results matching ""

    No results matching ""