5.4. Break and continue

Breaking/exiting loops

Sometimes we want to stop repeating the code block in a loop. We use the keyword break to do that. Let's look into the example below:

let breakPoint = 4
var countDown = 1
while breakPoint >= 0 {
    print("I will run!")
    
//  activating break point
    if countDown == breakPoint{
        print("I am tired now!")
        break
    }
    countDown += 1
}

Here the while loop is running infinitely if the value of breakPoint is greater than or equal to 0. So, we need to break it when the countDown reaches the breakPoint. Thats where we user the keyword break.

Skipping a block manually

Sometimes, we want to skip executing a repeated block for an iteration. Swift uses the keyword continue to do that. Let's look into the following example:

for number in 1...10 {
    //skipping the even numbers
    if number%2 == 0{
        continue
    }
    
    print("This an odd number:\(number)")
}

Here, we wanted to print the odd integers between 1 and 10. So, we are running a for loop from 1 to 10 and skipping the even numbers.

Last updated

Was this helpful?