Swift break

Welcome to Swift Tutorial. In this tutorial, we will learn about swift break keyword with the help of examples.

Swift break is used to break a loop prematurely. The normal functioning of a loop is that the loop is broken when the boolean expression it evaluates to false or the items in the collection are exhausted.

But break statement can be used to break a loop even before the condition is false or even before there are some elements remaining in the collection.

Break statement can be used to break while loop, repeat-while loop and also for loop.

Syntax – Swift break statement

Following is syntax of Swift break statement in a program.

</>
Copy
 break

In while loop

</>
Copy
 while boolean_expression {
     // some statements
     break
     // some other statements
 }

In for loop

</>
Copy
 for index in var {
     // some statements
     break
     // some other statements
 }

In repeat while loop

</>
Copy
 repeat {
     // some statements
     break
     // some other statements
 } while boolean_expression

Example 1 – Swift Break statement with While Loop

In this example, we will use break statement in swift while loop. For some reason, consider that we would like to break the loop when i becomes 3.

main.swift

</>
Copy
var i = 0

while i < 5 {

   if i==3 {
       break
   }

   print("i : \(i)")
   
   i = i + 1
}

print("rest of the statements")

Output

$swift while_loop_break_example.swift
i : 0
i : 1
i : 2
rest of the statements

Example 2 – Swift Break statement with For Loop

In this example, we will use break statement in swift for loop. For some reason, consider that we would like to break the loop when i becomes 3.

main.swift

</>
Copy
var i = 0

for i in 1..<6 {
   if i==3 {
       break
   }
   print("i : \(i)")
}

print("rest of the statements")

Output

$swift for_loop_break_example.swift
i : 1
i : 2
rest of the statements

Example 3 – Swift Break statement with Repeat While Loop

In this example, we will use break statement in swift repeat while loop. For some reason, consider that we would like to break the loop when i becomes 3.

main.swift

</>
Copy
var i = 0

repeat {
   if i==3 {
       break
   }
   print("i : \(i)")
   i = i + 1
} while i<5

print("rest of the statements")

Output

$swift repeat_while_loop_break_example.swift
i : 0
i : 1
i : 2
rest of the statements

Conclusion

In this Swift Tutorial, we have learned about Swift break statement with syntax and examples covering different scenarios.