Swift 条件语句

Swift 条件语句全解析(2025 版)

“if、switch、guard” —— 写出 清晰、安全、优雅 的流程控制代码!


一、Swift 条件语句概览

语句用途特点
if简单条件判断支持 else ifelse
switch多条件分支必须穷尽,支持区间、元组、where
guard提前退出提高可读性,避免“缩进地狱”
三元运算符 ?:简短条件表达式一行搞定

二、if 语句

基本语法

let temperature = 25

if temperature < 0 {
    print("冰冻")
} else if temperature < 10 {
    print("寒冷")
} else if temperature < 22 {
    print("凉爽")
} else {
    print("温暖")
}

条件必须是 Bool

// 错误!不能隐式判断
// if score { }

// 正确
if score > 0 { }
if !isLoggedIn { }

条件中声明变量(作用域仅在块内)

if let name = optionalName {
    print("Hello, \(name)")
}

三、switch 语句 —— Swift 的“核武器”

特点

  • 不需要 break(自动阻止穿透)
  • 必须穷尽所有情况
  • 支持 区间、元组、where、枚举、模式匹配

1. 基本使用

let grade = "B"

switch grade {
case "A":
    print("优秀")
case "B", "C":          // 多值匹配
    print("良好")
default:                // 必须有!除非穷尽
    print("需努力")
}

2. 区间匹配(Interval Matching)

let score = 88

switch score {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case 70..<80:
    print("C")
case 0..<60:
    print("F")
default:
    fatalError("无效分数")
}

3. 元组匹配(Tuple Matching)

let point = (3, 4)

switch point {
case (0, 0):
    print("原点")
case (_, 0):
    print("x轴")
case (0, _):
    print("y轴")
case let (x, y) where x == y:
    print("在 y=x 上")
case let (x, y) where x == -y:
    print("在 y=-x 上")
default:
    print("其他位置")
}

4. where 高级过滤

let number = 10

switch number {
case let x where x % 2 == 0:
    print("\(x) 是偶数")
case let x where x % 3 == 0:
    print("\(x) 是3的倍数")
default:
    print("\(x) 无特殊性质")
}

5. 枚举匹配

enum LoginResult {
    case success(name: String)
    case failure(reason: String)
    case loading
}

let result = LoginResult.success(name: "小明")

switch result {
case .success(let name):
    print("登录成功:\(name)")
case .failure(let reason):
    print("登录失败:\(reason)")
case .loading:
    print("登录中...")
}

6. 可选类型匹配

let optional: Int? = 42

switch optional {
case .some(let value):
    print("有值:\(value)")
case .none:
    print("无值")
}

7. fallthrough 强制穿透

let value = 1

switch value {
case 1:
    print("第一步")
    fallthrough
case 2:
    print("第二步")
default:
    break
}
// 输出:第一步 第二步

四、guard 语句 —— 提前退出神器

用途:在函数开头快速验证条件,不满足就 returnbreakcontinuethrow

基本语法

func login(username: String?, password: String?) {
    guard let username = username, !username.isEmpty else {
        print("用户名为空")
        return
    }

    guard let password = password, password.count >= 6 else {
        print("密码太短")
        return
    }

    // 安全使用 username 和 password
    print("登录:\(username)")
}

优点对比 if

if 写法guard 写法
缩进深代码扁平
变量作用域大变量作用域小
可读性差可读性强
// 坏:缩进地狱
if let user = user {
    if user.isActive {
        if user.hasPermission {
            // 业务逻辑
        }
    }
}

// 好:guard 提前退出
guard let user = user, user.isActive, user.hasPermission else {
    return
}
// 业务逻辑

五、三元运算符 ?:

let isAdult = age >= 18 ? true : false
let message = score >= 60 ? "及格" : "挂科"
let color = isOn ? UIColor.green : UIColor.red

建议:仅用于简单条件,复杂逻辑用 ifswitch


六、条件语句嵌套与组合

if let user = user, user.isLoggedIn && user.age > 18 {
    print("成人用户")
}

switch (age, isVIP) {
case (0..<13, _):
    print("儿童")
case (13..<18, false):
    print("青少年")
case (13..<18, true):
    print("VIP 青少年")
case (18..., _):
    print("成人")
}

七、模式匹配高级技巧

1. 值绑定 + where

switch temperature {
case let t where t < 0:
    print("零下 \(abs(t)) 度")
case 0..<10:
    print("很冷")
default:
    break
}

2. 类型模式

let obj: Any = "Hello"

switch obj {
case is String:
    print("是字符串:\(obj as! String)")
case let num as Int:
    print("是整数:\(num)")
default:
    break
}

八、实战案例:用户权限系统

enum UserRole {
    case guest, member, admin, owner
}

struct User {
    let name: String
    let role: UserRole
    let isBanned: Bool
    let loginCount: Int
}

func showDashboard(for user: User?) {
    // 1. 必须登录
    guard let user = user else {
        print("请先登录")
        return
    }

    // 2. 未被封禁
    guard !user.isBanned else {
        print("账户已封禁")
        return
    }

    // 3. 权限分支
    switch (user.role, user.loginCount) {
    case (.guest, _):
        print("游客模式")
    case (.member, 0..<10):
        print("新手会员:\(user.name)")
    case (.member, 10...):
        print("老会员:\(user.name)")
    case (.admin, _):
        print("管理员面板")
    case (.owner, _):
        print("系统所有者")
    }
}

九、条件语句最佳实践

场景推荐写法
简单布尔if isOn { }
可选解包guard let x = x else { return }
3+ 分支switch
区间判断switch score { case 90...100: }
提前退出guard
一行赋值let flag = condition ? a : b

十、常见错误 & 避坑

错误正确做法
switch 忘记 default除非穷尽,否则加 default
if 嵌套太深改用 guard
if let 变量污染作用域guard 限制作用域
switchbreak 滥用不需要 break
条件写成赋值if (flag = true) → 编译错误

十一、速查表

语句语法适用场景
ifif cond { } else { }简单条件
switchswitch v { case p: }多分支、模式匹配
guardguard cond else { return }提前验证
?:a ? b : c简单三元

十二、练习题(当场写!)

// 1. 用 switch 判断星期几(1-7)
func dayName(_ day: Int) -> String {
    // 返回 "星期一" 到 "星期日"
}

// 2. 用 guard 写一个安全除法函数
func safeDivide(_ a: Double, _ b: Double) -> Double? {
    // b==0 返回 nil
}

// 3. 用 switch + 元组 判断象限
func quadrant(x: Int, y: Int) -> String {
    // 返回 "第一象限"、"x轴"、"原点" 等
}

答案(展开查看)

点击查看答案

// 1.
func dayName(_ day: Int) -> String {
    switch day {
    case 1: return "星期一"
    case 2: return "星期二"
    case 3: return "星期三"
    case 4: return "星期四"
    case 5: return "星期五"
    case 6: return "星期六"
    case 7: return "星期日"
    default: return "无效"
    }
}

// 2.
func safeDivide(_ a: Double, _ b: Double) -> Double? {
    guard b != 0 else { return nil }
    return a / b
}

// 3.
func quadrant(x: Int, y: Int) -> String {
    switch (x, y) {
    case (0, 0): return "原点"
    case (0, _): return "y轴"
    case (_, 0): return "x轴"
    case let (x, y) where x > 0 && y > 0: return "第一象限"
    case let (x, y) where x < 0 && y > 0: return "第二象限"
    case let (x, y) where x < 0 && y < 0: return "第三象限"
    case let (x, y) where x > 0 && y < 0: return "第四象限"
    default: return "未知"
    }
}

总结:条件语句黄金法则

法则说明
1. 优先用 guard 做前置检查代码更扁平
2. 多于 3 个分支用 switch更清晰
3. switch 必须穷尽避免遗漏
4. 用区间和元组减少 if更强大
5. 三元运算符仅用于简单赋值避免复杂逻辑

你已完全掌握 Swift 条件语句!


回复关键词继续学习

  • Swift switch 模式匹配进阶
  • Swift 错误处理 vs guard
  • SwiftUI 条件渲染
  • Swift 状态机设计

现在就用 switch 写一个 BMI 计算器(偏瘦/正常/超重)!

文章已创建 2481

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部