Control statements are used to control the flow of the loop. The following constructs are used in loop control in swift.
break
statementcontinue
statementreturn
statementthrow
statementbreak
statementThe break
statement is used to terminate the loop as soon as it is encountered.
Let’s have a look at a code example below.
print("Break statement")for i in 1...8 {if i == 3 {break}print(i)}
The following will provide the code’s interpretation.
Line 1: Use the print
statement to print the name of the statement.
Line 3: Initialize a for
loop.
Line 4: Add an if
condition that will execute when the value of i
equals 3
.
Line 5: Run the break
statement.
Line 7: Print the current value of i
.
continue
statementThe continue
statement is used to skip the current iteration of the loop, and the control goes to the next iteration.
Let’s have a look at a code example below.
print("Continue statement")for i in 1...5 {if i == 3 {continue}print(i)}
The following will provide the code’s interpretation.
Line 1: Use the print
statement and print the name of the statement.
Line 3: Initialize a for
loop.
Line 4: Add an if
condition that will execute when the value of i
equals 3
.
Line 5: Run the continue
statement.
Line 7: Print the current value of i
.
return
statementThe return
statement is used to return/exit from a function.
print("Return statement")func test() {for i in 1...8 {if i == 3 {return}print(i)}}test()
The following will provide the code’s interpretation.
Line 1: Use the print
statement and print the name of the statement.
Line 3: Initialize a function named test()
.
Line 4: Initialize a for
loop.
Line 5: Add an if
condition that will execute when the value of i
equals 3
.
Line 6: Run the continue
statement.
Line 8: Print the current value of i
.
Line 12: Call the function test()
.
throw
statementThe throw
statement is used to raise/throw an exception.
Let’s have a look at a code example below.
print("throw statement")enum ValueError: Error {case runtimeError(String)}func test() throws {for i in 1...8 {if i == 3 {throw ValueError.runtimeError("Invalid value - " + i)}print(i)}}test()
The following will provide the code’s interpretation.
Line 1: Using the print
statement, print the statement name used in the example.
Line 3–5: Created an enum
.
Line 7: Initializing a function named test()
.
Line 8: Initializing a for
loop.
Line 9: Add an if
condition that will execute when the value of i
equals 3
.
Line 10: Run the throw
statement.
Line 12: Print the current value of i
.
Line 16: Call the function test()
.
Free Resources