switch 与 for 中的可选模式
使用 case let 模式匹配可选值。
switch 与 for 中的可选模式 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。
分支语句中的可选值
您可以直接对可选值使用分支语句。.some(value) 和 .none 分别匹配存在的值和 nil。
let value: Int? = 7
switch value {
case .some(let n):
print("Got \(n)")
case .none:
print("Nothing")
}? 的简写模式
写成 case let x? 是 .some(x) 的简写。末尾的 ? 表示“将值解包到 x 中”。
let value: String? = "Swift"
switch value {
case let text?:
print(text.uppercased())
case nil:
print("none")
}直接匹配 nil
您可以使用字面量 nil 匹配 nil 情况,而不是使用 .none,这样读起来更自然。
let value: Int? = nil
switch value {
case let n?:
print(n)
case nil:
print("no value")
}匹配特定值
您可以将特定的已解包值与通用的解包模式混合使用。
let status: Int? = 404
switch status {
case 200?:
print("OK")
case 404?:
print("Not Found")
case let code?:
print("Other: \(code)")
case nil:
print("No status")
}循环中的 for case let
遍历可选值时,for case let x? in array 会自动跳过 nil 元素,并解包其余元素。
let items: [Int?] = [1, nil, 3, nil, 5]
for case let n? in items {
print(n)
}for case 的过滤方式
模式 case let n? 只匹配非 nil 元素,因此循环体只会对存在的值执行。
let names: [String?] = ["Ann", nil, "Bo"]
for case let name? in names {
print(name.count)
}使用 if let 实现相同效果
您也可以在普通循环中使用 if let 实现相同效果,但 for case let x? 更简洁。
let items: [Int?] = [2, nil, 4]
for item in items {
if let item {
print(item)
}
}匹配枚举可选值
可选值模式可以与其他模式组合,例如匹配可选值内部的特定值。
let codes: [Int?] = [1, 2, nil, 3]
for case let c? in codes where c % 2 == 1 {
print("odd: \(c)")
}for case 中的 where
在 for case 循环中解包后,可以添加 where 子句进行进一步过滤。
let scores: [Int?] = [40, nil, 80, 95]
for case let s? in scores where s >= 80 {
print("high: \(s)")
}带 where 的分支语句
对可选值使用分支语句时,可以用 where 子句进一步限制已解包的绑定。
let value: Int? = 12
switch value {
case let n? where n > 10:
print("big: \(n)")
case let n?:
print("small: \(n)")
case nil:
print("none")
}为什么使用这些模式
可选值模式让您可以在一个完整结构中处理存在和缺失的值,减少分散在各处的 nil 检查。
let result: String? = nil
switch result {
case let r?:
print("Value: \(r)")
case nil:
print("Empty result")
}快速检查
测试可选值模式。
回顾:分支语句和循环中的可选值模式
在分支语句中使用 case let x?(.some 的简写)和 case nil,并使用 for case let x? 遍历非 nil 元素并解包它们;还可以选择使用 where 进一步限制条件。
let xs: [Int?] = [10, nil, 20]
for case let x? in xs { print(x) }用 AI 导师学习 Swift — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 122
- 课程
- 409
常见问题解答
「switch 与 for 中的可选模式」课时是免费的吗?
是的 — 「switch 与 for 中的可选模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。
「switch 与 for 中的可选模式」这节课中我会学到什么?
使用 case let 模式匹配可选值。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「switch 与 for 中的可选模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- if let 与简写绑定
- 使用 guard let 提前退出
- 绑定多个可选值
- switch 与 for 中的可选模式