swift-控制流程02-while循环

来源:互联网 发布:北杉切削液淘宝有卖吗 编辑:程序博客网 时间:2024/05/18 02:53

import UIKit


class ViewController: UIViewController {

  

  override func viewDidLoad() {

    super.viewDidLoad()

    

    /**

     while 循环执行一系列语句直到条件变成 false

     while 循环使用于第一次迭代时迭代值未知的情况下。

     Swift 提供两种 while循环形式:

     while 循环:在每次循环开始时判断条件是否为 true

     repeat-while 循环:在每次循环结束时判断条件是否为 true

     

     while 循环从判断一个循环条件开始:如果条件为true,重复执行一组代码,直到条件变为false

     */

    

    var index = 3

    

    while index > 0 {

      

      index--;

      print("index ==\(index)")

      

    }

    

    

    /**

     repeat-while while循环的另一种形式

     它和 while的区别是:先执行一次循环的代码块,再在判断循环条件,

     然后重复执行循环的代码块直到循环条件为 false

     */

    var index1 = 0

    

    repeat {

      

      index1++

      print("index1 ==\(index1)")

      

    } while index1 < 3

    

    

    /**

     在不同的条件下执行不同的代码块是非常有用的。要实现这个功能,需要使用条件语句。

     Swift 提供两种件语句类型:if语句和switch语句。

     当条件比较简单,可能的情况很少时,使用if语句。

     当条件比较复杂,可能情况较多时,使用switch语句

     */

     

     /**

     if 语句最简单的形式就是只包含一个条件,当且仅当该条件为 true时,才执行相关代码:

     */

    let age = 10

    if age < 18 {

      

      print("he or she is a teenage ")

      

    }

    

    /**

    if 语句允许二选一,也就是当条件为 false时,执行 else 语句

    这两条分支中总有一条会被执行

    */

    if age > 3 {

      

      print("he or she is not a baby")

      

    } else {

      

      print("he or she is a baby ")

      

    }

    

    /**

     你可以把多个 if语句链接在一起,像下面这样

     */

    let age1 = 17

    if age1 < 3 {

      

      print("it is a baby")

      

    } else if age1 <18 {

      

      print("it is a teenage")

      

    } else {

      

      print("it is old")

    }

    

    /**

    最后的else语句是可选的 

    可有可以没有

    */

    

  }

}


0 0