条件语句 #

一、if语句 #

1.1 基本if语句 #

swift
let score = 85

if score >= 60 {
    print("及格")
}

1.2 if-else语句 #

swift
let score = 55

if score >= 60 {
    print("及格")
} else {
    print("不及格")
}

1.3 if-else if-else语句 #

swift
let score = 85

if score >= 90 {
    print("优秀")
} else if score >= 80 {
    print("良好")
} else if score >= 60 {
    print("及格")
} else {
    print("不及格")
}

1.4 多条件判断 #

swift
let age = 25
let hasID = true

if age >= 18 && hasID {
    print("可以进入")
}

二、if语句与可选绑定 #

2.1 if let #

swift
let name: String? = "张三"

if let unwrappedName = name {
    print("名字是: \(unwrappedName)")
}

2.2 多个可选绑定 #

swift
let firstName: String? = "张"
let lastName: String? = "三"

if let first = firstName, let last = lastName {
    print("全名: \(first)\(last)")
}

2.3 可选绑定附加条件 #

swift
let age: Int? = 25

if let unwrappedAge = age, unwrappedAge >= 18 {
    print("成年人,年龄: \(unwrappedAge)")
}

三、switch语句 #

3.1 基本switch #

swift
let number = 2

switch number {
case 1:
    print("一")
case 2:
    print("二")
case 3:
    print("三")
default:
    print("其他")
}

3.2 多值匹配 #

swift
let char: Character = "a"

switch char {
case "a", "e", "i", "o", "u":
    print("元音")
default:
    print("辅音")
}

3.3 区间匹配 #

swift
let score = 85

switch score {
case 0..<60:
    print("不及格")
case 60..<80:
    print("及格")
case 80..<90:
    print("良好")
case 90...100:
    print("优秀")
default:
    print("无效分数")
}

3.4 元组匹配 #

swift
let point = (1, 1)

switch point {
case (0, 0):
    print("原点")
case (_, 0):
    print("在x轴上")
case (0, _):
    print("在y轴上")
case (-2...2, -2...2):
    print("在范围内")
default:
    print("在范围外")
}

3.5 值绑定 #

swift
let point = (2, 3)

switch point {
case (let x, 0):
    print("在x轴上,x = \(x)")
case (0, let y):
    print("在y轴上,y = \(y)")
case let (x, y):
    print("坐标: (\(x), \(y))")
}

3.6 where条件 #

swift
let point = (3, 4)

switch point {
case let (x, y) where x == y:
    print("在对角线上")
case let (x, y) where x == -y:
    print("在反对角线上")
case let (x, y):
    print("坐标: (\(x), \(y))")
}

四、fallthrough #

4.1 穿透执行 #

swift
let number = 2

switch number {
case 1:
    print("一")
    fallthrough
case 2:
    print("二")
    fallthrough
case 3:
    print("三")
default:
    print("其他")
}

4.2 注意事项 #

swift
let number = 2

switch number {
case 1:
    print("一")
case 2:
    print("二")
    fallthrough
case 3:
    print("三")
default:
    print("其他")
}

五、三元运算符 #

5.1 基本用法 #

swift
let score = 75
let result = score >= 60 ? "及格" : "不及格"
print(result)

5.2 嵌套三元运算符 #

swift
let score = 85
let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 60 ? "C" : "D"
print(grade)

5.3 实际应用 #

swift
let isLoggedIn = true
let buttonTitle = isLoggedIn ? "退出" : "登录"
print(buttonTitle)

六、Nil-Coalescing运算符 #

6.1 基本用法 #

swift
let name: String? = nil
let displayName = name ?? "匿名"
print(displayName)

6.2 链式使用 #

swift
let nickname: String? = nil
let username: String? = nil
let defaultName = "匿名"

let displayName = nickname ?? username ?? defaultName
print(displayName)

七、模式匹配 #

7.1 枚举匹配 #

swift
enum Direction {
    case north, south, east, west
}

let direction = Direction.north

switch direction {
case .north:
    print("向北")
case .south:
    print("向南")
case .east:
    print("向东")
case .west:
    print("向西")
}

7.2 可选模式 #

swift
let numbers: [Int?] = [1, 2, nil, 4, nil, 6]

for case let number? in numbers {
    print(number)
}

7.3 类型匹配 #

swift
let value: Any = "Hello"

switch value {
case is Int:
    print("是整数")
case is String:
    print("是字符串")
case is Double:
    print("是浮点数")
default:
    print("未知类型")
}

八、实际应用 #

8.1 计算器 #

swift
func calculate(_ a: Double, _ op: String, _ b: Double) -> Double? {
    switch op {
    case "+":
        return a + b
    case "-":
        return a - b
    case "*":
        return a * b
    case "/":
        return b != 0 ? a / b : nil
    default:
        return nil
    }
}

if let result = calculate(10, "+", 5) {
    print("结果: \(result)")
}

8.2 状态机 #

swift
enum State {
    case idle
    case loading
    case success(String)
    case error(String)
}

let state = State.success("数据加载完成")

switch state {
case .idle:
    print("空闲")
case .loading:
    print("加载中...")
case .success(let message):
    print("成功: \(message)")
case .error(let message):
    print("错误: \(message)")
}

8.3 验证输入 #

swift
func validateInput(_ input: String?) -> String {
    guard let input = input, !input.isEmpty else {
        return "输入不能为空"
    }
    
    guard input.count >= 3 else {
        return "输入长度至少3个字符"
    }
    
    guard input.count <= 20 else {
        return "输入长度不能超过20个字符"
    }
    
    return "输入有效"
}

print(validateInput(nil))
print(validateInput(""))
print(validateInput("ab"))
print(validateInput("valid input"))

九、最佳实践 #

9.1 使用guard提前返回 #

swift
func process(name: String?, age: Int?) {
    guard let name = name, !name.isEmpty else {
        print("名字无效")
        return
    }
    
    guard let age = age, age >= 0 else {
        print("年龄无效")
        return
    }
    
    print("处理: \(name), \(age)岁")
}

9.2 switch必须穷尽 #

swift
let number = 2

switch number {
case 1:
    print("一")
case 2:
    print("二")
default:
    break
}

9.3 避免深层嵌套 #

swift
func checkUser(user: User?) {
    guard let user = user else {
        return
    }
    
    guard user.isActive else {
        return
    }
    
    guard user.hasPermission else {
        return
    }
    
    print("用户验证通过")
}

十、总结 #

本章学习了Swift的条件语句:

  • if语句:基本条件判断
  • switch语句:多分支匹配
  • 模式匹配:灵活的模式匹配能力
  • 三元运算符:简洁的条件表达式

最佳实践:

  • 使用guard提前返回
  • switch必须穷尽所有情况
  • 避免深层嵌套
  • 使用模式匹配简化代码

下一章,我们将学习循环语句!

最后更新:2026-03-26