What are the loop control statements in Swift?
Control statements are used to control the flow of the loop. The following constructs are used in loop control in swift.
- The
breakstatement - The
continuestatement - The
returnstatement - The
throwstatement
The break statement
The break statement is used to terminate the loop as soon as it is encountered.
Code example
Let’s have a look at a code example below.
print("Break statement")for i in 1...8 {if i == 3 {break}print(i)}
Code explanation
The following will provide the code’s interpretation.
Line 1: Use the
printstatement to print the name of the statement.Line 3: Initialize a
forloop.Line 4: Add an
ifcondition that will execute when the value ofiequals3.Line 5: Run the
breakstatement.Line 7: Print the current value of
i.
The continue statement
The continue statement is used to skip the current iteration of the loop, and the control goes to the next iteration.
Code example
Let’s have a look at a code example below.
print("Continue statement")for i in 1...5 {if i == 3 {continue}print(i)}
Code explanation
The following will provide the code’s interpretation.
Line 1: Use the
printstatement and print the name of the statement.Line 3: Initialize a
forloop.Line 4: Add an
ifcondition that will execute when the value ofiequals3.Line 5: Run the
continuestatement.Line 7: Print the current value of
i.
The return statement
The return statement is used to return/exit from a function.
Code example
print("Return statement")func test() {for i in 1...8 {if i == 3 {return}print(i)}}test()
Code explanation
The following will provide the code’s interpretation.
Line 1: Use the
printstatement and print the name of the statement.Line 3: Initialize a function named
test().Line 4: Initialize a
forloop.Line 5: Add an
ifcondition that will execute when the value ofiequals3.Line 6: Run the
continuestatement.Line 8: Print the current value of
i.Line 12: Call the function
test().
The throw statement
The throw statement is used to raise/throw an exception.
Code example
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()
Code explanation
The following will provide the code’s interpretation.
Line 1: Using the
printstatement, 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
forloop.Line 9: Add an
ifcondition that will execute when the value ofiequals3.Line 10: Run the
throwstatement.Line 12: Print the current value of
i.Line 16: Call the function
test().
Free Resources