在 Swift 中执行 while 循环

如何在 Swift 中编写 do-while 循环?

51261 次浏览

下面是 Swift 的 repeat-while 循环的一般形式

repeat {
statements
} while condition

比如说,

repeat {
//take input from standard IO into variable n
} while n >= 0;

对于 n 的所有正值,这个循环将重复执行。

Swift 的 repeat-while 循环类似于其他语言中的 do-while 循环。 Repeat-while 循环是一个替代 while 循环。它首先单次通过循环块,然后考虑循环条件并重复循环,直到该条件显示为 false。

repeat
{
x--
}while x > 0

repeat-while循环,在考虑循环的条件(确切地说是 do-while循环所做的)之前,首先执行一次通过循环块的操作。

下面的代码片段是 repeat-while循环的一般形式,

repeat {
// your logic
} while [condition]

Repeat-while 循环,在考虑循环的条件(do-while 循环具体做什么)之前,首先对循环块执行一次遍历。

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