Swift: Swift 条件判断教程:if else 和 switch 语句详解
条件判断让程序根据不同的情况做出不同的反应,就像红绿灯根据交通状况改变信号。本课带你掌握 Swift 中 if else、switch 等所有条件控制方式。
1. 你将学到
- 使用 if / else if / else 进行条件分支控制
- 使用 switch 匹配多个值并进行模式匹配
- 使用区间运算符 ... 和 ..< 简化范围判断
- 使用 fallthrough 实现 switch 穿透
- 使用 where 子句给条件增加额外限制
2. 一个后端开发者的真实故事
(1) 痛点:多层身份权限判断让代码变成意大利面条
Bob 在一家 SaaS 公司开发用户权限系统。系统有 5 种用户角色(admin / editor / viewer / guest / banned),每种角色对 20 多个 API 端点的访问权限不同。Bob 最初用 15 层嵌套的 if-else 来实现: `swift if role == "admin" { if action == "delete" { // allow } else if action == "edit" { // allow } } else if role == "editor" { // 700 行重复代码... } 代码很快膨胀到 700 多行,新增一个角色就要改 5 个地方,Bob 花了一周才修复了一个因 if-else 顺序错误导致的安全漏洞。
(2) switch 的解法
Bob 改用 switch 语句重构权限系统: `swift let role = "editor" switch role { case "admin": print("Full access granted") case "editor": print("Read and write access") case "viewer", "guest": print("Read-only access") case "banned": print("Access denied") default: print("Unknown role") }
(3) 收益:代码瘦身 80%,逻辑一目了然
| 维度 | 15层 if-else | switch 重构后 |
|---|---|---|
| 代码行数 | 700+ 行 | 150 行 |
| 新增角色耗时 | 30 分钟 | 3 分钟 |
| 逻辑错误 | 3 个/月 | 0 个/月 |
| 可读性评分 | 3/10 | 9/10 |
3. if/else 条件语句
if/else 是 Swift 最基本的条件控制结构。它根据 Bool 值决定执行哪个代码块。 `mermaid graph TB A[Condition] -->|true| B[if block] A -->|false| C[else if / else block] B --> D[Continue] C --> D
| 语法 | 说明 | 示例 |
|---|---|---|
| if condition { } | 条件为 true 时执行 | if score >= 60 { } |
| if ... else { } | 条件为 false 时执行 else | if ... else { } |
| if ... else if ... else { } | 多条件依次判断 | if ... else if ... else { } |
(1) 基本 if 和 else
`swift let temperature = 30 if temperature > 25 { print("It's hot outside") } else { print("It's cool outside") }
(2) 多条件 else if
`swift let score = 85 if score >= 90 { print("Grade: A") } else if score >= 80 { print("Grade: B") } else if score >= 70 { print("Grade: C") } else if score >= 60 { print("Grade: D") } else { print("Grade: F") }
▶ 示例:用户登录状态检查
`swift // ============================================ // 根据用户登录状态显示不同消息 // ============================================ let isLoggedIn = true let hasProfile = false if isLoggedIn { print("Welcome back!") if hasProfile { print("Your profile is complete") } else { print("Please complete your profile") } } else { print("Please log in first") }
输出:
ext Welcome back! Please complete your profile
4. switch 多分支匹配
switch 是比 if-else 更强大的多分支匹配工具。Swift 的 switch 不需要写 break,匹配后自动退出。 `mermaid graph TB A[Value] --> B[case 1] A --> C[case 2] A --> D[case 3] A --> E[default] B --> F[Execute and Exit] C --> F D --> F E --> F
| 特性 | Swift switch | C / Java switch |
|---|---|---|
| 隐式 break | 自动(不用写 break) | 必须写 break |
| 区间匹配 | 支持 ... 和 ..< | 不支持 |
| 复合匹配 | 用逗号分隔多个值 | 靠 fallthrough |
| 必须穷尽 | 强制处理所有可能 | 不强制 |
| 默认分支 | 用 default | 用 default |
(1) 基本 switch 语法
`swift let fruit = "apple" switch fruit { case "apple": print("It's an apple") case "banana": print("It's a banana") case "orange": print("It's an orange") default: print("Unknown fruit") }
(2) 区间匹配和复合匹配
`swift let age = 25 switch age { case 0..<13: print("Child") case 13..<20: print("Teenager") case 20..<65: print("Adult") case 65...: print("Senior") default: print("Invalid age") }
▶ 示例:API 响应码处理
`swift // ============================================ // 用 switch 处理 HTTP 响应状态码 // ============================================ let statusCode = 404 switch statusCode { case 100..<200: print("Informational") case 200..<300: print("Success") case 300..<400: print("Redirection") case 400..<500: print("Client error") if statusCode == 404 { print("Resource not found") } case 500..<600: print("Server error") default: print("Unknown status code") }
输出:
ext Client error Resource not found
5. 高级控制:fallthrough、where 与三元运算符
Swift 提供了一些补充工具来让条件控制更灵活。
| 工具 | 用途 | 示例 |
|---|---|---|
| allthrough | switch 中穿透到下一个 case | case "a": fallthrough |
| where | 给条件增加额外过滤 | case let x where x > 10: |
| 三元 ? : | 简洁的二选一 | let max = a > b ? a : b |
(1) fallthrough 穿透
`swift let number = 2 switch number { case 1: print("One") case 2: print("Two") fallthrough case 3: print("Three or fell through from two") default: print("Other") }
(2) where 条件过滤
`swift let point = (x: 3, y: 4) switch point { case let (x, y) where x == y: print("On the diagonal") case let (x, y) where x > y: print("X is larger") case let (x, y) where x < y: print("Y is larger") default: print("On an axis") }
(3) 三元条件运算符
`swift let isMember = true let discount = isMember ? 0.2 : 0.0 print("Discount: (discount * 100)%")
▶ 示例:订单折扣计算器
`swift // ============================================ // 结合 if/switch/三元计算订单折扣 // ============================================ let orderTotal = 250.0 let customerTier = "gold" // 三元运算符:基础折扣 let baseDiscount = orderTotal > 100 ? 0.05 : 0.0 // switch:会员等级折扣 let tierDiscount: Double switch customerTier { case "platinum": tierDiscount = 0.20 case "gold": tierDiscount = 0.15 case "silver": tierDiscount = 0.10 default: tierDiscount = 0.0 } // if:叠加折扣上限 let totalDiscount = baseDiscount + tierDiscount let finalDiscount = totalDiscount > 0.3 ? 0.3 : totalDiscount let finalPrice = orderTotal * (1 - finalDiscount) print("Order total: $(orderTotal)") print("Tier: (customerTier)") print("Discount: (Int(finalDiscount * 100))%") print("Final price: $(finalPrice)")
输出:
ext Order total: .0 Tier: gold Discount: 20% Final price: .0
6. 完整示例:用户权限管理系统
`swift // ============================================ // 用户权限管理系统 // 综合运用 if/switch/where/三元运算符 // ============================================ import Foundation enum UserRole { case admin, editor, viewer, guest, banned } enum ActionResult { case granted, denied(String) } func checkPermission(role: UserRole, action: String, isOwner: Bool) -> ActionResult { switch role { case .banned: return .denied("Account is banned") case .admin: return .granted case .editor: if action == "delete" && !isOwner { return .denied("Only owners can delete") } return .granted case .viewer: switch (action, isOwner) { case (_, false): return .denied("Viewers cannot modify content") case ("read", true): return .granted default: return .denied("Unknown action") } case .guest: return action == "read" ? .granted : .denied("Guests can only read") } } let testCases = [ (UserRole.admin, "delete", false), (UserRole.editor, "delete", true), (UserRole.editor, "delete", false), (UserRole.viewer, "read", true), (UserRole.viewer, "write", false), (UserRole.guest, "read", false), (UserRole.banned, "read", false) ] for (role, action, isOwner) in testCases { let result = checkPermission(role: role, action: action, isOwner: isOwner) switch result { case .granted: print("[GRANTED] (role) can (action)") case .denied(let reason): print("[DENIED] (role) cannot (action) -- (reason)") } }
输出:
ext [GRANTED] admin can delete [GRANTED] editor can delete [DENIED] editor cannot delete -- Only owners can delete [GRANTED] viewer can read [DENIED] viewer cannot write -- Viewers cannot modify content [GRANTED] guest can read [DENIED] banned cannot read -- Account is banned
❓ 常见问题
📖 小节
- if/else 是最基础的条件控制,适合 2-3 个分支的简单判断
- switch 适合 3 个以上分支,支持区间匹配、复合匹配和值绑定
- switch 的 fallthrough 让代码穿透到下一 case,用于需要连续判断的场景
- where 子句为 switch case 和 for 循环增加额外的条件过滤
- 三元运算符 ? : 适合简洁的二选一赋值
- Swift switch 要求穷尽所有可能,增强了代码的安全性
📝 作业
- 基础题: 用 if/else 写一个体温分类程序: emp < 36.0 输出"低温",36.0...37.5 输出"正常",> 37.5 输出"发热"。
- 进阶题: 用 switch 重构第 1 题的体温分类,使其支持 emp < 35.0 时输出"危险低温"。要求用区间匹配语法实现。
- 挑战题: 创建一个支付手续费计算器。手续费规则:信用卡 2.5%(≥ 减 .5)、借记卡 1.0%(上限 )、PayPal 3.0%+.3。用 switch + where 实现。