What is the “break” keyword used for in Swift?

In Swift, the “break” keyword is used inside a loop to immediately terminate the execution of that block of code.

When encountering a “break” statement, the program jumps out of the loop and continues executing the next line of code after the loop or switch statement.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers {
    if number == 5 {
        break
    }
    print(number)
}

Quick notes

  • In this code, the loop iterates over each element in the “numbers” array.
  • If the current element is equal to 5, the “break” statement is executed and the loop is immediately terminated.
  • If the current element is any other number, the “print” statement is executed and the number is printed to the console.
  • This example demonstrates how the “break” keyword is used to terminate the execution of a loop when a certain condition is met.

In summary, the “break” keyword in Swift is used to immediately terminate the execution of a loop or switch statement and continues executing the next line of code after the loop or switch statement.

Leave a Reply

Your email address will not be published. Required fields are marked *