Day5 控制流(Control Flow)

** 1、 For-In 循环**

  • 你可以使用 for-in 循环来遍历一个集合中的所有元素,例如数字范围、数组中的元素或者字符串中的字符。
    for index in 1...5 {
    print("(index) times 5 is (index * 5)")
    }
    // 1 times 5 is 5
    // 2 times 5 is 10
    // 3 times 5 is 15
    // 4 times 5 is 20
    // 5 times 5 is 25

  • 如果你不需要区间序列内每一项的值,你可以使用下划线( _ )替代变量名来忽略这个值:

     let base = 3
    let power = 10
    var answer = 1
    for _ in 1...power {
    answer *= base
    }
    print("(base) to the power of (power) is (answer)")
    // 输出 "3 to the power of 10 is 59049"

  • 你也可以通过遍历一个字典来访问它的键值对。遍历字典时,字典的每项元素会以 (key, value) 元组的形式返 回,你可以在 for-in 循环中使用显式的常量名称来解读 (key, value) 元组。下面的例子中,字典的键(key)解 读为常量 animalName ,字典的值会被解读为常量 legCount :

     let numberOfLegsDic = ["spider": 8, "ant": 6, "cat": 4]
    for (animalName, legCount) in numberOfLegsDic {
    print("(animalName)s have (legCount) legs")
    }
    // ants have 6 legs
    // cats have 4 legs
    // spiders have 8 legs

** 2、 While 循环**

while 循环会一直运行一段语句直到条件变成 false 。这类循环适合使用在第一次迭代前,迭代次数未知的情况下。
• while循环,每次在循环开始时计算条件是否符合;
• repeat-while循环,每次在循环结束时计算条件是否符合。

while 循环从计算一个条件开始。如果条件为 true ,会重复运行一段语句,直到条件变为 false 。
while condition {
statements
}

Repeat-While

while 循环的另外一种形式是 repeat-while ,它和 while 的区别是在判断循环条件之前,先执行一次循环的代码块。然后重复循环直到条件为 false 。

注意: Swift语言的 repeat-while 循环和其他语言中的 do-while 循环是类似的。

下面是 repeat-while 循环的一般格式:

 repeat {
statements
} while condition

** 4、 条件语句**

  • If

      var temperatureInFahrenheit = 90
      if temperatureInFahrenheit <= 32 {
          print("It's very cold. Consider wearing a scarf.")
      } else if temperatureInFahrenheit >= 86 {
          print("It's really warm. Don't forget to wear sunscreen.")
      } else {
          print("It's not that cold. Wear a t-shirt.")
      }
      // 输出 "It's really warm. Don't forget to wear sunscreen."
    
  • Switch

    let someCharacter: Character = "z"
    switch someCharacter {
    case "a":
        print("The first letter of the alphabet")
    case "z":
        print("The last letter of the alphabet")
    default:
        print("Some other character")
    }
    // 输出 "The last letter of the alphabet"
    

注意:不存在隐式的贯穿
// 与 C 和 Objective-C 中的 switch 语句不同,在 Swift 中,当匹配的 case 分支中的代码执行完毕后,程序会终止 switch语句,而不会继续执行下一个 case 分支。这也就是说,不需要在 case 分支中显式地使用 break 语 句。这使得 switch 语句更安全、更易用,也避免了因忘记写 break 语句而产生的错误。

每一个 case 分支都必须包含至少一条语句。像下面这样书写代码是无效的,因为第一个 case 分支是空的:

 let anotherCharacter: Character = "a"
switch anotherCharacter {
// case "a": // 无效,这个分支下面没有语句
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// 这段代码会报编译错误

不像 C 语言里的 switch 语句,在 Swift 中, switch 语句不会一起匹配 "a" 和 "A" 。
相反的,上面的代码会引起编译期错误: case "a": 不包含任何可执行语句——这就避免了意外地从一个 case 分支贯穿到另外一个,使得代码更安全、也更直观。

  • 为了让单个case同时匹配 a 和 A ,可以将这个两个值组合成一个复合匹配,并且用逗号分开:

      let anotherCharacterA: Character = "a"
      switch anotherCharacterA {
      case "a", "A":
          print("The letter A")
      default:
          print("Not the letter A")
      }
      // 输出 "The letter A
    
  • 区间匹配
    case 分支的模式也可以是一个值的区间。下面的例子展示了如何使用区间匹配来输出任意数字对应的自然语言格式:

     let approximateCount = 62
    let countedThings = "moons orbiting Saturn"
    var naturalCount: String
    switch approximateCount {
    case 0:
    naturalCount = "no"
    case 1..<5:
    naturalCount = "a few"
    case 5..<12:
    naturalCount = "several"
    case 12..<100:
    naturalCount = "dozens of"
    case 100..<1000:
    naturalCount = "hundreds of"
    default:
    naturalCount = "many"
    }
    print("There are (naturalCount) (countedThings).")
    // 输出 "There are dozens of moons orbiting Saturn."

  • 元组
    我们可以使用元组在同一个 switch 语句中测试多个值。元组中的元素可以是值,也可以是区间。另外,使用下划线( _ )来匹配所有可能的值。
     let somePoint = (1, 1)
    switch somePoint {
    case (0, 0):
    print("(0, 0) is at the origin")
    case (_, 0):
    print("((somePoint.0), 0) is on the x-axis")
    case (0, _):
    print("(0, (somePoint.1)) is on the y-axis")
    case (-2...2, -2...2):
    print("((somePoint.0), (somePoint.1)) is inside the box")
    default:
    print("((somePoint.0), (somePoint.1)) is outside of the box")
    }
    // 输出 "(1, 1) is inside the box"
  • 复合匹配
    let someCharacterB: Character = "e"
    switch someCharacterB {
    case "a", "e", "i", "o", "u":
    print("(someCharacter) is a vowel")
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
    "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("(someCharacter) is a consonant")
    default:
    print("(someCharacter) is not a vowel or a consonant")
    }
    // 输出 "e is a vowel"
  • 控制转移语句
    • continue
    • break
    • fallthrough
    • return
    • throw

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)
// 输出 "grtmndsthnklk"

break 语句会立刻结束整个控制流的执行。当你想要更早的结束一个 switch 代码块或者一个循环体时,你都可以 使用 break 语句。
let numberSymbol: Character = "三"
// 简体中文里的数字 3
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).")
}
// 输出 "The integer value of 三 is 3."

  • 提前退出(guard)
    像 if 语句一样, guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 从句,如果条件不为真则执行 else 从句中的代码 。
    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"])
    // 输出 "Hello John!"
    // 输出 "I hope the weather is nice near you." greet(["name": "Jane", "location": "Cupertino"]) // 输出 "Hello Jane!"
    // 输出 "I hope the weather is nice in Cupertino."
  • 检测 API 可用性
     if #available(iOS 10, macOS 10.12, *) {
    // 在 iOS 使用 iOS 10 的 API, 在 macOS 使用 macOS 10.12 的 API
    } else {
    // 使用先前版本的 iOS 和 macOS 的 API
    }

你可能感兴趣的:(Day5 控制流(Control Flow))