[关闭]
@kakadee 2017-04-18T02:32:36.000000Z 字数 4381 阅读 1475

Swift 3.0 学习笔记-4-控制流

iOS Swift


前言:
swift3.0 学习笔记主要参考苹果开发者官网The Swift Programming Language (Swift 3.1)教程 以及 Swift 中文网
更纯粹的阅读的体验请移步至:
https://www.zybuluo.com/kakadee/note/726184



1. For-In Loops

使用for-in来遍历集合中的项目,比如数组的范围,排列中的项或者字符串中的字符。Swift 3.0 中已经移除了For-Condition-Increment的形式。
下面的例子打印了表中的5个元素

  1. for index in 1...5 {
  2. print("\(index) times 5 is \(index * 5)")
  3. }
  4. // 1 times 5 is 5
  5. // 2 times 5 is 10
  6. // 3 times 5 is 15
  7. // 4 times 5 is 20
  8. // 5 times 5 is 25

如果不需要范围的值,可以用下划线替代变量名来忽略这些值:

  1. let base = 3
  2. let power = 10
  3. var answer = 1
  4. for _ in 1...power {
  5. answer *= base
  6. }
  7. print("\(base) to the power of \(power) is \(answer)")
  8. // prints "3 to the power of 10 is 59049"

规定步长使用from:to:by:(不包含终点)

  1. let minutes = 60
  2. let minuteInterval = 5
  3. for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
  4. // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
  5. }

另一种方式,使用from:through:by: (包含终点)

  1. let hours = 12
  2. let hourInterval = 3
  3. for tickMark in stride(from: 3, through: hours, by: hourInterval) {
  4. // render the tick mark every 3 hours (3, 6, 9, 12)
  5. }

2. While Loops

while Loops的两种形式。

  1. while condition {
  2. statements
  3. }
  1. repeat {
  2. statements
  3. } while condition

3. Conditional Statements - 条件语句

If

没什么好说的。大家都会用

switch

  1. switch some value to consider {
  2. case value 1:
  3. respond to value 1
  4. case value 2,
  5. value 3:
  6. respond to value 2 or 3
  7. default:
  8. otherwise, do something else
  9. }

注意:swift 3.0 中的switch语句和C中的不一样。break不是必须的,当然加上亦可。另一个区别就是当前一条case判断是空的话不会自动跳到下一条case判断语句

  1. let anotherCharacter: Character = "a"
  2. switch anotherCharacter {
  3. case "a": // Invalid, the case has an empty body
  4. case "A":
  5. print("The letter A")
  6. default:
  7. print("Not the letter A")
  8. }
  9. // This will report a compile-time error.
  10. // 这种情况下会报错

如果想让switch的一条判定同时满足多种情况,可以放在一起写,用逗号分隔即可。

  1. let anotherCharacter: Character = "a"
  2. switch anotherCharacter {
  3. case "a", "A":
  4. print("The letter A")
  5. default:
  6. print("Not the letter A")
  7. }
  8. // Prints "The letter A"

范围匹配
switch中case的值可以检查他们内在的范围。这个例子使用数字范围可以提供任意大小数字的自然语言计数。

  1. et approximateCount = 62
  2. let countedThings = "moons orbiting Saturn"
  3. let naturalCount: String
  4. switch approximateCount {
  5. case 0:
  6. naturalCount = "no"
  7. case 1..<5:
  8. naturalCount = "a few"
  9. case 5..<12:
  10. naturalCount = "several"
  11. case 12..<100:
  12. naturalCount = "dozens of"
  13. case 100..<1000:
  14. naturalCount = "hundreds of"
  15. default:
  16. naturalCount = "many"
  17. }
  18. print("There are \(naturalCount) \(countedThings).")
  19. // Prints "There are dozens of moons orbiting Saturn."

元组
可以使用元组在相同的switch语句中测试多个值。每一个元组中的元素都可以试着和范围中不同的值进行匹配。另外,用下划线(_)标示符来匹配任意可能的值。

下面例子中使用一个点坐标(x,y),用元组型(Int, Int)来表示,可以在下面的图中分类出来:

  1. let somePoint = (1, 1)
  2. switch somePoint {
  3. case (0, 0):
  4. print("\(somePoint) is at the origin")
  5. case (_, 0):
  6. print("\(somePoint) is on the x-axis")
  7. case (0, _):
  8. print("\(somePoint) is on the y-axis")
  9. case (-2...2, -2...2):
  10. print("\(somePoint) is inside the box")
  11. default:
  12. print("\(somePoint) is outside of the box")
  13. }
  14. // Prints "(1, 1) is inside the box"

image_1bdvd5hcp11h41a1brue1kpl18vm9.png-17.9kB
Value Bindings 值绑定
一个switch的case能绑定用于匹配临时常量或变量值,在case的分支代码里使用。这就是value binding(值绑定),因为这些值在case的代码体中是临时常量或变量的“边界”。

下面的例子有一个点(x,y),用元组型(Int,Int)来表示,在图种展示出来如下:

  1. let anotherPoint = (2, 0)
  2. switch anotherPoint {
  3. case (let x, 0):
  4. print("on the x-axis with an x value of \(x)")
  5. case (0, let y):
  6. print("on the y-axis with a y value of \(y)")
  7. case let (x, y):
  8. print("somewhere else at (\(x), \(y))")
  9. }
  10. // Prints "on the x-axis with an x value of 2"

Where

switch的case能使用where子句来进一步判断条件。 下面的例子将点(x,y)在下图种分类:

  1. let yetAnotherPoint = (1, -1)
  2. switch yetAnotherPoint {
  3. case let (x, y) where x == y:
  4. print("(\(x), \(y)) is on the line x == y")
  5. case let (x, y) where x == -y:
  6. print("(\(x), \(y)) is on the line x == -y")
  7. case let (x, y):
  8. print("(\(x), \(y)) is just some arbitrary point")
  9. }
  10. // Prints "(1, -1) is on the line x == -y"

image_1bdvdclpm1oie1ndj1ecp69avorm.png-26.6kB
switch语句判断了点是否在绿色斜线上且x == y,或在紫色斜线上且x == -y,或都不是。

4. Control Transfer Statements - 控制转移语句

控制转移语句能改变已经执行代码的顺序,能使代码跳转到别的部分。Swift有四个句子:

Continue
Continue语句告诉循环体终止现在的操作,然后开始迭代下一个循环。好像在说“我这次迭代做完啦”,总之不会离开循环体。

Break
Break语句能立即终止整个控制流。可以根据你想要的在switch或循环语句里的任何地方终止整个执行。

Fallthrough
Swift中的Switch不会掉下到case的下方并进入下一个case。因此,整个switch语句会在第一个匹配的case完成后结束。相反,C语言要求你在每个case的末尾插入一个break来防止掉入。相比于C语言,Swift的switch禁止默认掉入让更加简洁和可控,这样避免了执行多个case的错误。
如果你确实需要C式的掉入特性,你可以使用fallthrough关键词。

  1. let integerToDescribe = 5
  2. var description = "The number \(integerToDescribe) is"
  3. switch integerToDescribe {
  4. case 2, 3, 5, 7, 11, 13, 17, 19:
  5. description += " a prime number, and also" fallthrough
  6. default:
  7. description += " an integer."
  8. }
  9. println(description)
  10. // prints "The number 5 is a prime number, and also an integer."

Labeled Statements - 标签语句
你可以嵌套循环或在switch语句中嵌套其他的循环,Swift语句种的switch可以创建复杂的控制流结构。 然而,循环和switch语句都可以过早地使用break。因此,有时明确的使用break来终止代码很有用。类似的,如果你有多个嵌套的循环,continue会更有用。

为了做到这一点,你可以用statement label来标记循环或switch,与break或continue语句一起使用这个标签来终止或继续标记语句的执行。

  1. label name: while condition {
  2. statements
  3. }

这样,你就可以用这个标签来代替这个循环语句。

  1. var count = 0;
  2. countLoop : while count < 5 {
  3. count += 1;
  4. if (count == 3) {
  5. break countLoop
  6. }
  7. }
  8. print(count)
  9. // 3

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注