Swift repeat…while循环

Swift repeat…while循环

forwhile 循环不同,它们在循环的顶部测试循环条件的同时, repeat…while 循环在循环的底部检查它的条件。

一个 repeat…while 循环与while循环类似,唯一的区别是 repeat…while 循环保证至少执行一次。

语法

Swift 4中 repeat…while 循环的语法为:

repeat {
   statement(s);
} 
while( condition );

需要注意的是条件表达式出现在循环的末尾,所以循环中的语句在条件被测试之前执行一次。如果条件为真,控制流跳回到 repeat ,循环中的语句再次执行。这个过程重复直到给定条件变为假。

数字0,字符串’0’和””,空列表()和未定义的值在布尔上下文中都是 false ,而其他所有值都是 true 。通过 !not 对真值进行取反会返回一个特殊的假值。

流程图

Swift repeat...while循环

示例

var index = 10

repeat {
   print( "Value of index is \(index)")
   index = index + 1
}
while index < 20

当以上代码被执行时,它产生以下结果−

Value of index is 10
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 15
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程