iOS.& Swift Books Swift学徒

4
先进的控制流程 由MATT Galloway撰写

In the previous chapter, you learned how to control the flow of execution using the decision-making powers of if statements and the while loop. In this chapter, you’ll continue to learn how to control the flow of execution. You’ll learn about another loop known as the for loop.

循环可能听起来不太有趣,但它们在计算机程序中非常常见。例如,您可能有代码从云下载图像;使用循环,您可以多次运行该次数以下载整个照片库。或者如果您有多个计算机控制字符的游戏,则可能需要循环来完成每个循环,并确保它知道下一步该做什么。

You’ll also learn about 转变 statements, which are particularly powerful in Swift. They let you inspect a value and decide what to do based on that value. They’re incredibly powerful when used with some advanced Swift features such as pattern matching.

可数范围

Before you dive into the for 环形 statement, you need to know about the 可数范围 数据类型,允许您表示一系列可数整数。让我们看看两种类型的范围。

首先,有 可数关闭范围,您代表如此:

let closedRange = 0...5

这 three dots (...) indicate that this range is closed, which means the range goes from 0 to 5 inclusive. That’s the numbers (0, 1, 2, 3, 4, 5).

第二,有 可数半开放程,您代表如此:

let halfOpenRange = 0..<5

Here, you replace the three dots with two dots and a less-than sign (..<). Half-open means the range goes from 0 up to, but not including, 5. That’s the numbers (0, 1, 2, 3, 4).

Both open and half-open ranges must always be increasing. In other words, the second number must always be greater than or equal to the first. Countable ranges are commonly used in both for loops and 转变 statements, which means that throughout the rest of the chapter, you’ll use ranges as well!

随机插曲

编程中的共同需求是能够生成随机的nmbers。和Swift Provercis内置于语言的功能,这很方便!

while Int.random(in: 1...6) != 6 {
  print("Not a six")
}

对于循环

In the previous chapter you looked at while loops. Now that you know about ranges, it’s time to look at another type of loop: the for loop。这可能是您将看到的最常见的循环,并且您将使用它来运行代码一定次数。

for <CONSTANT> in <COUNTABLE RANGE> {
  <LOOP CODE>
}
let count = 10
var sum = 0
for i in 1...count {
  sum += i
}

sum = 1
var lastSum = 0

for _ in 0..<count {
  let temp = sum
  sum = sum + lastSum
  lastSum = temp
}
sum = 0
for i in 1...count where i % 2 == 1 {
  sum += i
}

继续并标记陈述

Sometimes you’d like to skip a loop iteration for a particular case without breaking out of the loop entirely. You can do this with the 继续 statement, which immediately ends the current iteration of the loop and starts the next iteration.

sum = 0

for row in 0..<8 {
  if row % 2 == 0 {
    continue
  }

  for column in 0..<8 {
    sum += row * column
  }
}

sum = 0

rowLoop: for row in 0..<8 {
  columnLoop: for column in 0..<8 {
    if row == column {
      continue rowLoop
    }
    sum += row * column
  }
}

迷你练习

sum = 0
for row in 0..<8 {
  if row % 2 == 0 {
    continue
  }
  for column in 0..<8 {
    sum += row * column
  }
}

切换陈述

You can also control flow via the 转变 statement. It executes different code depending on the value of a variable or constant. Here’s a 转变 statement that acts on an integer:

let number = 10

switch number {
case 0:
  print("Zero")
default:
  print("Non-zero")
}
 转变  number {
case 10:
  print("It’s ten!")
default:
  break
}
let string = "Dog"

switch string {
case "Cat", "Dog":
  print("Animal is a house pet.")
default:
  print("Animal is not a house pet.")
}

高级交换机语句

You can also give your 转变 statements more than one case. In the previous chapter, you saw an if statement that used multiple else clauses to convert an hour of the day to a string describing that part of the day. You could rewrite that more succinctly with a 转变 statement, like so:

let hourOfDay = 12
var timeOfDay = ""

switch hourOfDay {
case 0, 1, 2, 3, 4, 5:
  timeOfDay = "Early morning"
case 6, 7, 8, 9, 10, 11:
  timeOfDay = "Morning"
case 12, 13, 14, 15, 16:
  timeOfDay = "Afternoon"
case 17, 18, 19:
  timeOfDay = "Evening"
case 20, 21, 22, 23:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}

print(timeOfDay)
 转变  hourOfDay {
case 0...5:
  timeOfDay = "Early morning"
case 6...11:
  timeOfDay = "Morning"
case 12...16:
  timeOfDay = "Afternoon"
case 17...19:
  timeOfDay = "Evening"
case 20..<24:
  timeOfDay = "Late evening"
default:
  timeOfDay = "INVALID HOUR!"
}
 转变  number {
case let x where x % 2 == 0:
  print("Even")
default:
  print("Odd")
}
 转变  number {
case _ where number % 2 == 0:
  print("Even")
default:
  print("Odd")
}

部分匹配

Another way you can use 转变 statements with matching to great effect is as follows:

let coordinates = (x: 3, y: 2, z: 5)

switch coordinates {
case (0, 0, 0): // 1
  print("Origin")
case (_, 0, 0): // 2
  print("On the x-axis.")
case (0, _, 0): // 3
  print("On the y-axis.")
case (0, 0, _): // 4
  print("On the z-axis.")
default:        // 5
  print("Somewhere in space")
}
 转变  coordinates {
case (0, 0, 0):
  print("Origin")
case (let x, 0, 0):
  print("On the x-axis at x = \(x)")
case (0, let y, 0):
  print("On the y-axis at y = \(y)")
case (0, 0, let z):
  print("On the z-axis at z = \(z)")
case let (x, y, z):
  print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
 转变  coordinates {
case let (x, y, _) where y == x:
  print("Along the y = x line.")
case let (x, y, _) where y == x * x:
  print("Along the y = x^2 line.")
default:
  break
}

迷你练习

挑战

在继续前进之前,以下是测试您对先进控制流程的知识的一些挑战。如果您尝试自己解决这些问题,最好是,如果您陷入困境,则可以使用解决方案。这些随下载或在介绍中列出的印刷书的源代码链接中提供。

挑战1:多少次

In the following for loop, what will be the value of sum, and how many iterations will happen?

var sum = 0
for i in 0...5 {
  sum += i
}

挑战2:算上信

In the while 环形 below, how many instances of “a” will there be in aLotOfAs? Hint: aLotOfAs.count tells you how many characters are in the string aLotOfAs.

var aLotOfAs = ""
while aLotOfAs.count < 10 {
  aLotOfAs += "a"
}

挑战3:什么将打印

Consider the following 转变 statement:

 转变  coordinates {
case let (x, y, z) where x == y && y == z:
  print("x = y = z")
case (_, _, 0):
  print("On the x/y plane")
case (_, 0, _):
  print("On the x/z plane")
case (0, _, _):
  print("On the y/z plane")
default:
  print("Nothing special")
}
let coordinates = (1, 5, 0)
let coordinates = (2, 2, 2)
let coordinates = (3, 0, 1)
let coordinates = (3, 2, 5)
let coordinates = (0, 2, 4)

挑战4:封闭范围大小

关闭范围永远不会是空的。为什么?

挑战5:最后的倒计时

Print a countdown from 10 to 0. (Note: do not use the reversed() method, which will be introduced later.)

挑战6:打印序列

Print 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0. (Note: do not use the stride(from:by:to:) function, which will be introduced later.)

关键点

  • 您可以使用 可数范围 要创建一系列整数,递增以从一个值移动到另一个值。
  • 封闭的范围 包括开始和终端值。
  • 半开线 包括启动值并在最终值之前停止一个。
  • 对于循环 允许您迭代范围。
  • 继续 声明允许您完成循环的当前迭代并开始下一个迭代。
  • 标记的陈述 let you use break and 继续 on an outer loop.
  • 你用 转变 根据变量或常量的值来确定要运行的代码的语句。
  • 这 power of a 转变 statement comes from leveraging 模式匹配 使用复杂规则比较值。

有一个技术问题?想报告一个错误吗? 您可以向官方书籍论坛中的书籍作者提出问题和报告错误 这里 .

有反馈分享在线阅读体验吗? 如果您有关于UI,UX,突出显示或或读者的OTH壮举的反馈,您可以将其发送到设计团队,其中表格如下所示:

© 2021 Razeware LLC

您可以免费读取,本章的部分显示为 混淆了 文本。解锁这本书,以及我们整个书籍和视频目录,带有Raywenderlich.com的专业订阅。

现在解锁

要突出或记笔记,您需要在订阅中拥有这本书或自行购买。