乐闻世界logo
搜索文章和话题

Swift 中的枚举是什么?如何使用关联值和原始值?

2月21日 15:10

Swift 中的枚举是什么?如何使用关联值和原始值?枚举支持哪些高级特性?

Swift 中的枚举是一种定义一组相关值的类型,比其他语言的枚举更强大。Swift 的枚举可以包含关联值、原始值,并且可以定义方法和计算属性。

基本枚举定义:

swift
enum 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)

枚举方法:

swift
enum 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 } } }

计算属性:

swift
enum 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 协议:

swift
enum CompassPoint: CaseIterable { case north, south, east, west } let numberOfCases = CompassPoint.allCases.count for direction in CompassPoint.allCases { print(direction) }

Comparable 协议:

swift
enum 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

枚举的高级特性:

  1. 支持泛型
  2. 支持协议
  3. 支持扩展
  4. 支持初始化器
  5. 支持下标

最佳实践:

  1. 使用枚举表示有限的、相关的值集合
  2. 使用关联值传递额外的数据
  3. 使用原始值表示固定的值
  4. 为枚举添加方法提高可读性
  5. 使用递归枚举处理树形结构
标签:Swift