11 控制流之switch语句

在上一章中,我们讨论了 if 语句的基本用法,if 语句是控制流中最基本的结构之一。今天,我们将深入探讨另一种强大的控制流语句——switch 语句。

switch 语句允许我们根据一个变量的值来控制程序的流向,与 if 语句相比,switch 更加清晰和易于维护。它能够处理多个条件,非常适合用于多分支选择结构。

switch 语法

switch 语句的基本语法结构如下:

1
2
3
4
5
6
7
8
switch value {
case pattern1:
// 代码块
case pattern2:
// 代码块
default:
// 默认代码块
}

这里的 value 是我们需要进行判断的值,而 case 后面的 pattern 则是我们要匹配的模式。如果某个模式匹配成功,将执行对应的代码块。如果没有任何模式匹配成功,那么将执行 default 中的代码块。

以下是一个简单的示例:

1
2
3
4
5
6
7
8
9
10
11
12
let number = 3

switch number {
case 1:
print("Number is one")
case 2:
print("Number is two")
case 3:
print("Number is three")
default:
print("Number is not in the range of 1 to 3")
}

在这个例子中,变量 number 的值为 3,因此程序输出 Number is three

模式匹配

值的区间

switch 中,我们不仅可以匹配单一的值,还可以匹配值的范围。这使得 switch 语句非常方便。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let score = 85

switch score {
case 0..<60:
print("Failing")
case 60..<80:
print("Passing")
case 80..<90:
print("Good")
case 90...100:
print("Excellent")
default:
print("Invalid score")
}

在这个例子中,根据 score 的范围输出不同的评语。

元组匹配

switch 语句还允许我们使用元组进行复杂的匹配。例如:

1
2
3
4
5
6
7
8
9
10
11
12
let point = (1, 1)

switch point {
case (0, 0):
print("Origin")
case (let x, 0):
print("X-axis at \(x)")
case (0, let y):
print("Y-axis at \(y)")
case (let x, let y):
print("Point at (\(x), \(y))")
}

在这个例子中,我们通过 case 语句匹配元组的不同情况,并使用 let 关键字来提取值。

值绑定

switch 语句还可以通过值绑定,将匹配的值绑定到变量以便在对应的代码块中使用。例如:

1
2
3
4
5
6
7
8
9
10
let animal = "rabbit"

switch animal {
case "cat", "dog":
print("This is a domestic animal.")
case "lion", "tiger":
print("This is a wild animal.")
case let x:
print("This is a \(x).")
}

在这个例子中,对于没有明确匹配到的动物名,我们将其赋值给 x 变量并输出。

fallthrough 控制

switch 语句中,可以使用 fallthrough 关键字来实现穿透行为,允许程序在匹配到某个 case 后继续执行下一个 case 的代码块。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
let value = 1

switch value {
case 1:
print("One")
fallthrough
case 2:
print("Two")
case 3:
print("Three")
default:
print("Unknown")
}

在上述代码中,由于 fallthrough 的存在,当 value1 时,不仅会输出 One,还会继续输出 Two,结果将是:

1
2
One
Two

总结

本章中,我们深入探讨了 switch 语句的多种用法及特性,包括值的匹配、区间匹配、元组匹配、值绑定和 fallthrough 控制。通过这些知识,您可以构建更具可读性和可维护性的代码结构。

在下节课中,我们将进一步讨论控制流中的循环语句,通过学习循环,您将能够执行重复的任务和迭代数据。继续期待我们的下一个主题吧!

11 控制流之switch语句

https://zglg.work/swift-lang-zero/11/

作者

IT教程网(郭震)

发布于

2024-08-15

更新于

2024-08-16

许可协议

分享转发

交流

更多教程加公众号

更多教程加公众号

加入星球获取PDF

加入星球获取PDF

打卡评论