Swift Break Statement
In Swift, the break statement is used to immediately exit a loop, switch, or labeled statement. When executed, the break statement will terminate the nearest enclosing loop, switch, or labeled statement and continue executing the program from the next statement.
Syntax
The basic syntax of the break statement in Swift is as follows:
break
Example
Here is an example of using the break statement in a loop:
for i in 1...5 {
if i == 3 {
break
}
print(i)
}
// Output: 1 2
Output
In the above example, the loop executes five times, but when the value of i
is 3, the break
statement is executed, causing the loop to terminate. The output of the program is 1 2
, which are the values of i
before the loop was terminated.
Explanation
The break
statement causes the nearest enclosing loop to terminate immediately. In the above example, the loop is terminated when the value of i
is 3, and the program jumps to the next statement after the loop.
Use
The break
statement is useful when you want to terminate a loop early, based on some condition. It can also be used to exit a switch statement or a labeled statement. The break
statement can be used in conjunction with control statements like if
, while
, repeat-while
, and switch
.
Important Points
- The
break
statement is used to immediately exit a loop, switch, or labeled statement. - When executed, the
break
statement will terminate the nearest enclosing loop, switch, or labeled statement. - The
break
statement can be used in conjunction with control statements likeif
,while
,repeat-while
, andswitch
.
Summary
The break
statement is an important control flow statement in Swift that allows you to immediately exit a loop, switch, or labeled statement. It can be used in conjunction with other control statements to provide powerful and flexible control flow in your programs.