Swift 中的枚举是什么?如何使用关联值和原始值?
Swift 中的枚举是什么?如何使用关联值和原始值?枚举支持哪些高级特性?Swift 中的枚举是一种定义一组相关值的类型,比其他语言的枚举更强大。Swift 的枚举可以包含关联值、原始值,并且可以定义方法和计算属性。基本枚举定义:enum CompassPoint { case north case south case east case west}var direction = CompassPoint.northdirection = .south关联值:每个枚举成员可以存储不同类型的关联值类似于带有附加数据的枚举示例: 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 访问原始值必须是字符串、字符、整数或浮点数示例: enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } let earth = Planet(rawValue: 3) print(earth?.rawValue) // Optional(3)枚举方法: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 } }}计算属性: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 关键字标记允许枚举成员引用枚举本身示例: 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 协议:enum CompassPoint: CaseIterable { case north, south, east, west}let numberOfCases = CompassPoint.allCases.countfor direction in CompassPoint.allCases { print(direction)}Comparable 协议: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.highlet priority2 = Priority.lowprint(priority1 > priority2) // true枚举的高级特性:支持泛型支持协议支持扩展支持初始化器支持下标最佳实践:使用枚举表示有限的、相关的值集合使用关联值传递额外的数据使用原始值表示固定的值为枚举添加方法提高可读性使用递归枚举处理树形结构