88

How to write a do-while loop in Swift?

0

4 Answers 4

159

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.

0
17

repeat-while loop, performs a single pass through the loop block first before considering the loop's condition (exactly what do-while loop does).

var i = Int()
repeat {
//below line was fixed to say print("\(i) * \(i) = \(i * i)")
   print("\(i) * \(i) = \(i * i)")
    i += 1

} while i <= 10
0
13

repeat-while loop, performs a single pass through the loop block first before considering the loop's condition (exactly what do-while loop does).

Code snippet below is a general form of a repeat-while loop,

repeat {
  // your logic
} while [condition]
2

swift's repeat-while loop is similar to a do-while loop in other language . The repeat-while loop is a alternate while loop.It first makes a single pass through the loop block ,then considers the loop condition and repeats the loop till the condition shows as false.

repeat 
{
x--
}while x > 0

Not the answer you're looking for? Browse other questions tagged or ask your own question.