控制转移 #
一、控制转移概述 #
Swift提供以下控制转移语句:
- continue:跳过当前迭代,继续下一次
- break:终止整个循环
- fallthrough:switch穿透执行
- return:返回函数
- throw:抛出错误
二、continue语句 #
2.1 基本用法 #
swift
for i in 1...10 {
if i % 2 == 0 {
continue
}
print(i)
}
2.2 过滤特定值 #
swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers {
if number == 5 {
continue
}
print(number)
}
2.3 处理可选值 #
swift
let items: [String?] = ["A", nil, "B", nil, "C"]
for item in items {
guard let item = item else {
continue
}
print(item)
}
2.4 复杂条件 #
swift
let students = [
("张三", 85),
("李四", 55),
("王五", 90),
("赵六", 45)
]
for (name, score) in students {
guard score >= 60 else {
continue
}
print("\(name): \(score)分 - 及格")
}
三、break语句 #
3.1 基本用法 #
swift
for i in 1...10 {
if i == 5 {
break
}
print(i)
}
3.2 查找元素 #
swift
let numbers = [3, 7, 2, 9, 5, 1]
let target = 9
var found = false
var index = -1
for (i, number) in numbers.enumerated() {
if number == target {
found = true
index = i
break
}
}
print(found ? "找到在索引\(index)" : "未找到")
3.3 条件终止 #
swift
var sum = 0
for i in 1...100 {
sum += i
if sum > 1000 {
print("当i=\(i)时,sum=\(sum)超过1000")
break
}
}
3.4 while循环中使用 #
swift
var count = 0
while true {
count += 1
if count > 5 {
break
}
print(count)
}
四、带标签的语句 #
4.1 标签语法 #
swift
labelName: for i in 1...3 {
for j in 1...3 {
print("(\(i), \(j))")
}
}
4.2 带标签的break #
swift
outerLoop: for i in 1...3 {
for j in 1...3 {
if i == 2 && j == 2 {
break outerLoop
}
print("(\(i), \(j))")
}
}
4.3 带标签的continue #
swift
outerLoop: for i in 1...3 {
for j in 1...3 {
if j == 2 {
continue outerLoop
}
print("(\(i), \(j))")
}
}
4.4 实际应用 #
swift
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let target = 5
search: for (i, row) in matrix.enumerated() {
for (j, value) in row.enumerated() {
if value == target {
print("找到\(target)在位置(\(i), \(j))")
break search
}
}
}
五、fallthrough语句 #
5.1 基本用法 #
swift
let number = 2
switch number {
case 1:
print("一")
fallthrough
case 2:
print("二")
fallthrough
case 3:
print("三")
default:
print("其他")
}
5.2 模拟C风格switch #
swift
let char: Character = "a"
switch char {
case "a":
print("是a")
fallthrough
case "A":
print("是A或a")
default:
break
}
5.3 注意事项 #
swift
let number = 2
switch number {
case 1:
print("一")
case 2:
print("二")
fallthrough
case 3:
print("三")
default:
print("其他")
}
六、return语句 #
6.1 基本用法 #
swift
func greet(name: String) -> String {
return "Hello, \(name)!"
}
print(greet(name: "Swift"))
6.2 提前返回 #
swift
func divide(_ a: Int, by b: Int) -> Int? {
if b == 0 {
return nil
}
return a / b
}
if let result = divide(10, by: 2) {
print(result)
}
6.3 隐式返回 #
swift
func add(_ a: Int, _ b: Int) -> Int {
a + b
}
print(add(1, 2))
七、throw语句 #
7.1 基本用法 #
swift
enum ValidationError: Error {
case emptyInput
case invalidLength
}
func validate(_ input: String) throws {
guard !input.isEmpty else {
throw ValidationError.emptyInput
}
guard input.count >= 3 else {
throw ValidationError.invalidLength
}
}
do {
try validate("ab")
} catch {
print(error)
}
7.2 实际应用 #
swift
enum NetworkError: Error {
case noConnection
case timeout
case serverError(Int)
}
func fetchData() throws -> String {
let connected = false
guard connected else {
throw NetworkError.noConnection
}
return "Data"
}
do {
let data = try fetchData()
print(data)
} catch NetworkError.noConnection {
print("无网络连接")
} catch {
print("其他错误: \(error)")
}
八、实际应用 #
8.1 表单验证 #
swift
func validateForm(name: String?, email: String?, age: Int?) -> Bool {
guard let name = name, !name.isEmpty else {
print("名字不能为空")
return false
}
guard let email = email, email.contains("@") else {
print("邮箱格式不正确")
return false
}
guard let age = age, age >= 18 else {
print("年龄必须大于等于18岁")
return false
}
return true
}
8.2 搜索算法 #
swift
func binarySearch(_ array: [Int], target: Int) -> Int? {
var left = 0
var right = array.count - 1
while left <= right {
let mid = (left + right) / 2
if array[mid] == target {
return mid
} else if array[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return nil
}
let sortedArray = [1, 3, 5, 7, 9, 11, 13]
if let index = binarySearch(sortedArray, target: 7) {
print("找到在索引\(index)")
}
8.3 状态机 #
swift
enum State {
case idle
case connecting
case connected
case disconnecting
}
var state = State.idle
func processState() {
switch state {
case .idle:
print("空闲状态")
state = .connecting
case .connecting:
print("连接中...")
state = .connected
case .connected:
print("已连接")
state = .disconnecting
case .disconnecting:
print("断开连接")
state = .idle
}
}
for _ in 1...5 {
processState()
}
九、最佳实践 #
9.1 使用guard提前退出 #
swift
func process(data: [Int]?) {
guard let data = data, !data.isEmpty else {
return
}
for item in data {
print(item)
}
}
9.2 避免深层嵌套 #
swift
func validate(user: User?) -> Bool {
guard let user = user else { return false }
guard user.isActive else { return false }
guard user.hasPermission else { return false }
return true
}
9.3 合理使用标签 #
swift
search: for i in 0..<matrix.count {
for j in 0..<matrix[i].count {
if matrix[i][j] == target {
return (i, j)
}
}
}
十、总结 #
本章学习了Swift的控制转移语句:
- continue:跳过当前迭代
- break:终止循环
- fallthrough:switch穿透
- return:函数返回
- throw:抛出错误
最佳实践:
- 使用guard提前退出
- 避免深层嵌套
- 合理使用标签
- 保持代码可读性
下一章,我们将学习guard语句!
最后更新:2026-03-26