DEV Community

Too Leng
Too Leng

Posted on

【ChaoCode】 Swift 基礎篇 11:Switch 作業



1. 基础语法switch / case / default
swift
复制
let value = 3
switch value {
case 1:
    print("一")
case 2:
    print("二")
default:
    print("其他") // 输出 "其他"
}
特点

不需要显式写 breakSwift  case 默认不会穿透)。

必须覆盖所有可能性或使用 default)。

2. fallthrough强制穿透到下一 case
swift
复制
let num = 2
switch num {
case 2:
    print("匹配到2")
    fallthrough // 强制穿透到下一个 case
case 3:
    print("继续执行3的逻辑") // 会输出
default:
    break
}
// 输出:
// 匹配到2
// 继续执行3的逻辑
3. break 的用法
提前退出某个 case

swift
复制
let score = 85
switch score {
case 0...60:
    print("不及格")
case 61...100:
    if score == 100 {
        print("满分!")
        break // 提前退出
    }
    print("及格")
default:
    break
}
4. 匹配元组Tuple
swift
复制
let point = (1, 2)
switch point {
case (0, 0):
    print("原点")
case (_, 0): // 忽略纵坐标
    print("在X轴上")
case (0, let y): // 值绑定(绑定纵坐标)
    print("在Y轴上,y=\(y)")
case (-2...2, -2...2):
    print("在 (-2~2, -2~2) 范围内")
default:
    print("其他位置")
}
5. 匹配范围
swift
复制
let temperature = 25
switch temperature {
case ..<0:
    print("结冰")
case 0...20:
    print("凉爽")
case 21...30:
    print("温暖") // 输出
case 31...:
    print("炎热")
default:
    break
}
6. 同一 case 中多个条件类似 if  ||
swift
复制
let month = 3
switch month {
case 1, 2, 12: // 匹配多个值
    print("冬季")
case 3...5:
    print("春季") // 输出
case 6...8:
    print("夏季")
case 9...11:
    print("秋季")
default:
    break
}
7. case ... where 的用法
swift
复制
let number = 7
switch number {
case let x where x % 2 == 0: // 匹配偶数
    print("\(x) 是偶数")
case let x where x % 2 != 0: // 匹配奇数
    print("\(x) 是奇数") // 输出
default:
    break
}

// 简化写法:
switch number {
case _ where number > 10: // 忽略绑定,直接判断条件
    print("大于10")
default:
    print("小于等于10")
}
Enter fullscreen mode Exit fullscreen mode

If 和 Switch 的「條件判斷方式」差別是什麼?

if 是判斷是否為 true;switch 是判斷兩個值是否相等。
哪些情況用 switch 語句可以不用寫 default?
Swift 可以明確地把每一種 case 都個別列出來的類型,像是布林和 enum。

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more