Swift心得笔记之控制流

2020-01-08 22:51:14于海丽


let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {
case let (x, y) where x == y:
  println("((x), (y)) is on the line x == y")
case let (x, y) where x == -y:
  println("((x), (y)) is on the line x == -y")
case let (x, y):
  println("((x), (y)) is just some arbitrary point")
}
// "(1, -1) is on the line x == -y”

Control Transfer Statements

Swift 有四个控制转移状态:

continue - 针对 loop ,直接进行下一次循环迭代。告诉循环体:我这次循环已经结束了。
break - 针对 control flow (loop + switch),直接结束整个控制流。在 loop 中会跳出当前 loop ,在 switch 中是跳出当前 switch 。如果 switch 中某个 case 你实在不想进行任何处理,你可以直接在里面加上 break 来忽略。
fallthrough - 在 switch 中,将代码引至下一个 case 而不是默认的跳出 switch。
return - 函数中使用
其他

看到一个有趣的东西:Swift Cheat Sheet,里面是纯粹的代码片段,如果突然短路忘了语法可以来看看。

比如 Control Flow 部分,有如下代码,基本覆盖了所有的点:


// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
  if value == 1 {
    println("One!")
  } else {
    println("Not one!")
  }
}

// for loop (dictionary)
var dict = [
  "name": "Steve Jobs",
  "title": "CEO",
  "company": "Apple"
]
for (key, value) in dict {
  println("(key): (value)")
}

// for loop (range)
for i in -1...1 { // [-1, 0, 1]
  println(i)
}
// use .. to exclude the last number

// for loop (ignoring the current value of the range on each iteration of the loop)
for _ in 1...3 {
  // Do something three times.
}

// while loop
var i = 1
while i < 1000 {
  i *= 2
}

// do-while loop
do {
  println("hello")
} while 1 == 2

// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
  let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
  let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
  let vegetableComment = "Is it a spicy (x)?"
default: // required (in order to cover all possible input)
  let vegetableComment = "Everything tastes good in soup."
}

// Switch to validate plist content
let city:Dictionary<String, AnyObject> = [
  "name" : "Qingdao",
  "population" : 2_721_000,
  "abbr" : "QD"
]
switch (city["name"], city["population"], city["abbr"]) {
  case (.Some(let cityName as NSString),
    .Some(let pop as NSNumber),
    .Some(let abbr as NSString))
  where abbr.length == 2:
    println("City Name: (cityName) | Abbr.:(abbr) Population: (pop)")
  default:
    println("Not a valid city")
}