In Swift, a while loop is used to execute a block of code repeatedly as long as a certain condition is true. The general syntax of a while loop in Swift is as follows:
main.swift46 chars4 lines
Here, condition
is the test that is evaluated before each iteration of the loop. As long as condition
remains true, the loop will continue to execute. Once condition
becomes false, the loop will terminate and program execution will continue with the statement that follows the loop.
For example, the following Swift code uses a while loop to print the value of i
until i
is greater than or equal to 10:
main.swift52 chars7 lines
This will output:
main.swift20 chars11 lines
In this example, the loop will continue to execute as long as i
is less than 10. Inside the loop, the current value of i
is printed to the console, and then i
is incremented by 1. When i
reaches 10 or greater, the loop condition becomes false and the loop terminates.
gistlibby LogSnag