条件语句


  • if 语句
  (1) 只包含一个条件语句:
      if 判断条件 {
        语句
      }

  (2) 包含两个条件语句:
      if 判断条件 {
        语句 1
      } else {
        语句 2
      }

  (3) 包含多个条件语句:
      if 判断条件 {
        语句 1
      } else if 判断条件 {
        语句 2
      } else if 判断条件 {
        语句 3
      }
        ...
        else if 判断条件 {
         语句 m   
      } else {
         语句 n
      }

   1. 必须显式地指明具体的判断条件是 true 还是 false2. if 语句条件的 () 可以省略,但 {} 不能省略;
      3. 当最后没任务执行的情况下,else if 中的最后的 else 可以省略。

   if-let 语句
    语法格式:
    if let 常量名 = 可选变量名 {
      语句
    }

    let oAge: Int? = 20
    if let age = oAge, age > 18 {
      // 使用常量 age
      print(age)
    }
  • guard 语句:用于函数中
  guard 判断条件 else {
    语句 1
    return
  }
  语句组

   1. 当判断条件为 true 的时候,跳过 else 语句的内容,直接执行语句组;
     2. 当判断条件为 false 的时候,执行 else 语句的内容,其跳转语句一般为 return, break, continue, 
         和 throw3. guard 在函数里面使用。

   guard-let 语句
    语法格式:
    guard let 常量名 = 可选变量名 ... else {
      语句 1
      return
    }
    语句组

    func guardCase() {
     let oAge: Int? = 20
     guard let age = oAge, age > 18 else {
       print("年龄小于 18 岁")
       return
     }
     // 代码执行到这里,age 一定有值且 age > 18
     print(age) 
    }
  • switch 语句:通过和具体的值匹配去执行相应的代码。
  语法格式:
  switch (表达式) {
    case 常量表达式 1:
         语句 1
    case 常量表达式 2:
         语句 2
         ...
    case 常量表达式 n:
         语句 n
    default:
         语句 n + 1 
  }

  // 可以匹配多个常量表达式,case 后面的任意一种模式匹配的时候,这条分支就会被匹配
  let rank = "A"
   switch rank {
    case "A", "B":
      print("优")
    case "C":
      print("差")
    default:
      print("没有评定级别")
   }

   // 在 case 中定义变量不用加大括号
   let rank = "A"
    switch rank {
     case "A":
     var number = 10
     print("优")
    case "B":
     print("良")
    case "C":
     print("差")
    default:
     print("没有评级")
   }

   // 可以匹配浮点型
   let m = 3.14
   switch m {
    case 3.14:
     print("π")
    default:
     print("not π") 
   }

   // 可以匹配字符串
  let nameString = "why"
   switch nameString {
    case "why":
     print("英语老师")
    case "wxx":
     print("体育老师")
  default:
     print("其他老师")
  }

  // 可以匹配区间
  let number = 20
   switch number {
    case 1...9:
     print("个位数")
    case 10...99:
     print("十位数")
    default:
     print("其它数")
  }

  // 可以匹配元组,元组中的元素可以是值,也可以是区间,也可以使用下划线(_)来匹配所有可能的值
  let coordinate = (0, 0)
   switch coordinate {
    case (1, 0):
     print("原点")
    case (_, 0):
     print("x轴")
    case (0, _):
     print("y轴")
    case (-2...2, -2...2):
     print("矩形区域")
    default:
     print("没有任何目标区域")
  }

  // 值绑定:case 分支允许将匹配的值绑定到一个临时的常量或者变量,并且在 case 分支体内使用
  let anotherPoint = (2, 0)
   switch anotherPoint {
    case (let x, 0):
     print("on the x-axis with an x value of \(x)")
    case (0, let y):
     print("on the y-axis with an y value of \(y)")
    case (let x, let y):
     print("somewhere else at (\(x), \(y))")
  }

  // where:case 分支的模式可以使用 where 语句来判断额外的条件
  let yetAnotherPoint = (1, -1)
   switch yetAnotherPoint {
    case let (x, y) where x == y:
     print("(\(x), \(y)) is on the line x == y")
    case let (x, y) where x == -y:
     print("(\(x), \(y)) is on the line x == -y")
    case let (x, y):
     print("(\(x), \(y)) is just some arbitrary point")
  }

  /* switch 语句中的 break:当在一个 switch 代码块中使用 break 时,会立即中断该 switch 代码块
     的执行,并且跳转到表示 switch 代码块结束的大括号(})后的第一行代码 */
  let numberSymbol: Character = "三"
  var possibleIntegerValue: Int?
  switch numberSymbol {
   case "1", "?", "一":
    possibleIntegerValue = 1
   case "2", "?", "二":
    possibleIntegerValue = 2
   case "3", "?", "三":
    possibleIntegerValue = 3
   case "4", "?", "四":
    possibleIntegerValue = 4
   default:
    break
  }
  if let integerValue = possibleIntegerValue {
    print("The integer value of \(numberSymbol) is \(integerValue).")
  } else {
    print("An integer value could not be found for \(numberSymbol).")
  }

  // 穿透特性:在每个需要该特性的 case 分支中使用 fallthrough 关键字
  let integerToDescribe = 5
  var description = "The number \(integerToDescribe) is "
  switch integerToDescribe {
   case 2, 3, 5, 7, 11, 13, 17, 19:
    description += "a prime number, and also"
    fallthrough
   default:
    description += "an integer."
  }  
  print(description)

循环语句


  • for-in 语句
   应用场景:用来遍历一个集合中的所有元素。

  语法格式:
  for index in collection {
    // 代码块
  }

  // 遍历区间
  for i in 1...5 {
    print(i)
  }

  // 遍历数组
  let names = ["Anna", "Alex", "Brian", "Jack"]
  for name in names {
    print("Hello, \(name)!")
  }

  // 遍历字典
  let numberOfLegs = ["spider" : 8, "ant" : 6, "cat" : 4]
  for (animalName, legCount) in numberOfLegs {
    print("\(animalName)s have \(letCount) legs")
  }

  // 声明变量接受元素
  var j = 0
  for j in 2...6 {
    print(j)
  }
  print(j)

  // 使用下划线(_)来替代 index
  let base = 3
  let power = 10
  var answer = 1
  for _ in 1...power {
    answer *= base
  }
  print("\(base) to the power of \(power) is \(answer)")

   1. index 是一个每次循环遍历开始时被自动赋值的常量,无需使用 let 关键字声明;
     2. index 常量只存在于循环的生命周期里,如果要扩大作用域,必须在循环之前进行常量或者变量声明。
  • while 循环
  语法格式:
  while 循环条件 {
    // 代码块
  }
   若判断条件为 true ,则执行 while 循环中的代码块,否则跳出 while 循环

  蛇与梯子游戏,示例代码:
  let finalSquare = 25
  var board = [Int](repeating: 0, count: finalSquare + 1)
  board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
  board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
  var square = 0
  while square < finalSquare {
  // 使用 1~6 随机数模拟掷骰子效果
  let diceRoll = Int(arc4random() % 6) + 1
  print(diceRoll)
  // 根据点数移动角色
  square += diceRoll
  if square < board.count {
    // 如果玩家还在棋盘上,则遵循游戏规则
    square += board[square]
    }      
  }
  print("Game over!")

   死循环是无法靠自身控制终止的循环,一般写法:
    while true {
      statement(s)
    }

   repeat-while 循环
    语法格式:
    repeat {
      // code
    } while condition
    * 先执行一次循环的代码;
    ** 重复循环直到条件为 false。

  蛇和梯子游戏改写,示例代码:
  let finalSquare = 25
  var board = [Int](repeating: 0, count: finalSquare + 1)
  board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
  board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
  var square = 0
  repeat {
    // 顺着梯子爬上去或者顺着蛇滑下去
    square += board[square]
    // 掷骰子
    let diceRoll = Int(arc4random() % 6) + 1
    print(diceRoll) 
    // 根据点数移动
    square += diceRoll
  } while square < finalSquare
  print("Game over!")

控制转移语句


  • 定义:改变代码的执行顺序,通过它可以实现代码的跳转
  • 分类:returnbreakcontinuethrowfallthrough
continue:告诉一个循环体立刻停止本次循环,重新开始下次循环;
    let puzzleInput = "great minds think alike"
    var puzzleOutput = ""
    for character in puzzleInput.characters {
      switch character {
        case "a", "e", "i", "o", "u", " ":
          continue
        default:
          puzzleOutput.append(character)
      }
    }
    print(puzzleOutput)

   break:会立刻结束整个控制流的执行。
    1. 循环语句中 break:
       (1) 当在一个循环体中使用 break 时;
        (2) 会立刻中断该循环体的执行,然后跳转到表示循环体结束的大括号(})后的第一行代码;
         (3) 不会再有本次循环的代码被执行,也不会再有下次的循环产生。

    2. switch 语句中的 break:
       (1) 当在一个 switch 代码块中使用 break 时;
        (2) 会立即中断该 switch 代码块的执行;
         (3) 并且跳转到表示 switch 代码块结束的大括号(})后的第一行代码。

带标签的语句


  • 应用场景:在循环体和条件语句中嵌套循环体和条件语句来创造复杂的控制流结构。
  label name: while condition { statements }

  示例代码:
  let finalSquare = 25
  var board = [Int](repeating: 0, count: finalSquare + 1)
  board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
  board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
  var square = 0
  var diceRoll = 0
  gameLoop: while square != finalSquare {
  diceRoll = Int(arc4random() % 6) + 1
  print(diceRoll)
  switch square + diceRoll {
   case finalSquare:
     // 骰子数刚好使玩家移动到最终的方格里,游戏结束
     break gameLoop
   case let newSquare where newSquare > finalSquare:
     // 骰子数将会使玩家的移动超出最后的方格,那么这种移动是不合法的,玩家需要重新掷骰子
     continue gameLoop
   default:
     // 合法移动,做正常的处理
     square += diceRoll
     square += board[square]
    }
   }
   print("Game over!")

提前退出


  • 应用场景:类似守卫一样,提升代码的可读性。
  func greet(person: [String: String]) {
   guard let name = person["name"] else {
     return
   }
   print("Hello \(name)")
   guard let location = person["location"] else {
     print("I hope the weather is nice near you.")
     return
   }
   print("I hope the weather is nice in \(location).")
  }
  greet(person: ["name": "John"])
  greet(person: ["name": "Jane", "location": "Cupertino"])

检测 API 可用性


  语法格式:
  if #available(platform name version, ... , *) {
    // APIs 可用,语句将执行
  } else {
    // APIs 不可用,语句将不执行 
  }

  示例代码:
  if #available(iOS 10, macOS 10.12, *) {
    // 在 iOS 使用 iOS 10(或更高) 的 API, 在 macOS 使用 macOS 10.12(或更高) 的 API
  } else {
    // 使用先前版本的 iOS 和 macOS 的 API
  }

results matching ""

    No results matching ""