How to write a do-while loop in Swift?
The do statement is used to introduce a new scope and can optionally contain one or more catch clauses, which contain patterns that match against defined error conditions. Variables and constants declared in the scope of a do statement can be accessed only within that scope.
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
The do while loop is an exit controlled loop, where even if the test condition is false, the loop body will be executed at least once. An example of such a scenario would be when you want to exit your program depending on the user input.
Here’s the general form of a repeat-while loop for Swift
repeat { statements } while condition
For example,
repeat { //take input from standard IO into variable n } while n >= 0;
This loop will repeat for all positive values of n.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With