Swift 中的枚举是什么?如何使用关联值和原始值?枚举支持哪些高级特性?
Swift 中的枚举是一种定义一组相关值的类型,比其他语言的枚举更强大。Swift 的枚举可以包含关联值、原始值,并且可以定义方法和计算属性。
基本枚举定义:
swiftenum CompassPoint { case north case south case east case west } var direction = CompassPoint.north direction = .south
关联值:
- 每个枚举成员可以存储不同类型的关联值
- 类似于带有附加数据的枚举
- 示例:
swift
enum Barcode { case upc(Int, Int, Int, Int) case qrCode(String) } var productBarcode = Barcode.upc(8, 85909, 51226, 3) productBarcode = .qrCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .upc(let numberSystem, let manufacturer, let product, let check): print("UPC: \(numberSystem), \(manufacturer), \(product), \(check)") case .qrCode(let productCode): print("QR code: \(productCode)") }
原始值:
- 枚举成员可以有相同类型的预填充值
- 使用
rawValue访问原始值 - 必须是字符串、字符、整数或浮点数
- 示例:
swift
enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } let earth = Planet(rawValue: 3) print(earth?.rawValue) // Optional(3)
枚举方法:
swiftenum TrafficLight { case red, yellow, green func description() -> String { switch self { case .red: return "Stop" case .yellow: return "Caution" case .green: return "Go" } } mutating func next() { switch self { case .red: self = .green case .yellow: self = .red case .green: self = .yellow } } }
计算属性:
swiftenum Rectangle { case width(height: Double) case height(width: Double) var area: Double { switch self { case .width(let height): return height * 10 case .height(let width): return width * 5 } } }
递归枚举:
- 使用
indirect关键字标记 - 允许枚举成员引用枚举本身
- 示例:
swift
enum ArithmeticExpression { case number(Int) indirect case addition(ArithmeticExpression, ArithmeticExpression) indirect case multiplication(ArithmeticExpression, ArithmeticExpression) } let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
CaseIterable 协议:
swiftenum CompassPoint: CaseIterable { case north, south, east, west } let numberOfCases = CompassPoint.allCases.count for direction in CompassPoint.allCases { print(direction) }
Comparable 协议:
swiftenum Priority: Int, Comparable { case low = 1 case medium = 2 case high = 3 static func < (lhs: Priority, rhs: Priority) -> Bool { return lhs.rawValue < rhs.rawValue } } let priority1 = Priority.high let priority2 = Priority.low print(priority1 > priority2) // true
枚举的高级特性:
- 支持泛型
- 支持协议
- 支持扩展
- 支持初始化器
- 支持下标
最佳实践:
- 使用枚举表示有限的、相关的值集合
- 使用关联值传递额外的数据
- 使用原始值表示固定的值
- 为枚举添加方法提高可读性
- 使用递归枚举处理树形结构