Swift – continue statement


Swift – Continue Statement



”;


The continue statement is designed to be used inside the loop to skip the code inside the loop block and process the next iteration. With the help of the continue statement, we can bypass the remaining code present inside the loop for a certain iteration according to the given condition.

For a for loop, the continue statement causes the conditional test and increments the portions of the loop to execute. For while and do…while loops, the continue statement causes the program control to pass to the conditional tests.

Syntax

Following is the syntax of the continue statement −


continue

Flow Diagram

The following flow diagram will show how the continue statement works −


Continue Statement

Example

Swift program to demonstrate the use of continue statement.


import Foundation

let nums = [30, 2, 14, 7, 19, 11, 13, 10]

// Loop to print even numbers
for n in nums {
   if n % 2 != 0 {
    
      // Skip the code for odd numbers
      continue
   }

   // It will execute only for even numbers
   print("Even Number: (n)")
}

Output

It will produce the following output −


Even Number: 30
Even Number: 2
Even Number: 14
Even Number: 10

Example

Swift program to skip -4 from the given array using continue statement.


import Foundation

let arr = [11, 12, 23, -4, 88, 92, 34, 2]

for x in arr {
   if x == -4 {
    
      // When x = -4, skip the rest of the loop  
      continue
   }
   print("Value: (x)")
}

Output

It will produce the following output −


Value: 11
Value: 12
Value: 23
Value: 88
Value: 92
Value: 34
Value: 2

Example

Swift program to skip city names whose length is more than 5 characters using continue statement.


import Foundation

let city = ["Delhi", "Mumbai", "Jaipur", "Pune", "Goa"]

for x in city {
   if x.count > 5 {
    
      // Skip those cities whose word count is more than 5 characters 
      continue
   }
   print("City names: (x)")
}

Output


City names: Delhi
City names: Pune
City names: Goa

Advertisements

”;

Leave a Reply

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