Appearance
Swift 入门(11):枚举
枚举(
enum)是 Swift 中非常常见的语法结构,用来表示一组有限的、相关的值。
它比许多其他语言中的枚举更强大,支持关联值、原始值,还能扩展方法。
1. 基本用法
swift
enum Direction {
case north
case south
case east
case west
}
let d = Direction.north
print(d) // north你也可以写在一行:
swift
enum Direction { case north, south, east, west }2. 搭配 switch 使用
swift
func move(_ dir: Direction) {
switch dir {
case .north:
print("向北走")
case .south:
print("向南走")
case .east:
print("向东走")
case .west:
print("向西走")
}
}
move(.east) // 向东走
switch必须覆盖所有枚举的情况,否则编译报错。
3. 枚举的原始值
枚举的每个 case 可以绑定一个 原始值(Raw Value),常见于数字或字符串。
swift
enum Weekday: Int {
case monday = 1, tuesday, wednesday, thursday, friday, saturday, sunday
}
print(Weekday.friday.rawValue) // 5
if let day = Weekday(rawValue: 7) {
print(day) // sunday
}4. 枚举的关联值
有时 case 需要携带不同的数据,这时可以用 关联值。
swift
enum LoginState {
case success(user: String)
case failure(error: String)
}
let result = LoginState.success(user: "Alice")
switch result {
case .success(let user):
print("登录成功:\(user)")
case .failure(let error):
print("失败:\(error)")
}5. 枚举的方法
枚举可以像类和结构体一样添加方法。
swift
enum TrafficLight {
case red, yellow, green
func action() -> String {
switch self {
case .red: return "停"
case .yellow: return "等"
case .green: return "走"
}
}
}
print(TrafficLight.green.action()) // 走总结
enum用来表示有限集合。- 搭配
switch使用非常常见。 - 可以有 原始值 和 关联值。
- 可以定义 方法,功能接近类和结构体。
Swift 的枚举很灵活,不只是常量集合,更像“轻量的数据类型”。