0Pricing
Swift Academy · 课时

switch——穷尽性、范围、元组、where

使用功能强大的 switch ,处理穷尽的分支、数值范围、元组匹配和 where 子句。

switch——穷尽性、范围、元组、where 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 3 节课。

简介

Swift 中的 switch 表达力强且安全:它要求覆盖所有情况,并支持范围、元组和 where 子句。

基本 switch

Switch 可以匹配字符串,并且必须通过 case 或 default 覆盖所有情况。

let fruit = "apple"
switch fruit {
case "apple": print("Good fiber")
case "banana": print("Potassium")
default: print("Tasty fruit")
}

范围

可以使用类似 90...100(闭范围)和 80..<90(半开范围)的范围。

let score = 73
switch score {
case 90...100: print("A")
case 80..<90: print("B")
case 60..<80: print("C")
default: print("D or below")
}

元组匹配

匹配元组并使用 let 绑定值;添加 where 以指定额外条件。

let point = (x: 1, y: -1)
switch point {
case (0, 0): print("Origin")
case (let x, 0): print("On X-axis, x=\\(x)")
case (0, let y): print("On Y-axis, y=\\(y)")
case (1... , let y) where y < 0: print("x >= 1 and y negative")
default: print("Somewhere else")
}

where 子句

使用 where 细化模式,同时让逻辑保持内联且易于阅读。

let number = 12
switch number {
case let n where n % 2 == 0: print("\\(n) is even")
default: print("odd")
}

贯穿行为

Swift 默认不会贯穿执行后续 case,因此可以减少错误。如有需要,请明确使用 fallthrough。

Switch 安全性

快速检查:是什么让 Swift 的 switch 比许多语言更安全?

回顾

回顾:Swift switch 要求覆盖所有情况,支持范围和元组,并且可以添加 where 条件;默认不会隐式贯穿执行。

常见问题解答

「switch——穷尽性、范围、元组、where」课时是免费的吗?

是的 — 「switch——穷尽性、范围、元组、where」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 3 节课。

「switch——穷尽性、范围、元组、where」这节课中我会学到什么?

使用功能强大的 switch ,处理穷尽的分支、数值范围、元组匹配和 where 子句。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。

「switch——穷尽性、范围、元组、where」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. if/else 基础
  2. switch——穷尽性、范围、元组、where
  3. 循环——for-in、while、repeat-while
← 返回 Swift Academy