Swift - While 循环

  • 简述

    while 只要给定条件为真,Swift 4 编程语言中的循环语句就会重复执行目标语句。
  • 句法

    的语法 while Swift 4 编程语言中的循环是 -
    
    while condition {
       statement(s)
    }
    
    这里 statement(s)可以是单个语句或语句块。这condition可以是任何表达式。当条件为真时循环进行迭代。当条件变为假时,程序控制将传递到紧跟在循环后面的那一行。
    数字 0、字符串 '0' 和 ""、空的 list() 和 undef 都是 false 在布尔上下文中,所有其他值都是 true. 否定真值! 要么 not 返回一个特殊的假值。
  • 流程图

    While 循环
    while循环的关键在于循环可能永远不会运行。当条件被测试并且结果为假时,将跳过循环体并执行while循环之后的第一条语句。
  • 例子

    
    var index = 10
    while index < 20 {
       print( "Value of index is \(index)")
       index = index + 1
    }
    
    这里我们使用比较运算符 < 来比较变量的值 index 反对 20。当索引值小于 20 时, 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