在 Swift 中,枚举(Enum)是一种定义一组相关值的通用类型。枚举为一组相关值提供了一个共同的类型,并且可以用于更安全、更清晰地编写代码。

以下是关于 Swift 枚举的基本信息和使用方法:

枚举的基本定义
// 简单的枚举定义
enum CompassPoint {
    case north
    case south
    case east
    case west
}

// 使用枚举成员
var direction = CompassPoint.north
direction = .east

关联值(Associated Values)

枚举成员可以关联具体的值,使得枚举更加灵活:
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

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).")
}

原始值(Raw Values)

枚举成员可以关联原始值,这些原始值必须是相同类型的:
enum Planet: Int {
    case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}

let earthOrder = Planet.earth.rawValue  // 输出 3

递归枚举

枚举也可以是递归的,即枚举成员具有相同的枚举类型作为关联值:
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))

方法和属性

枚举可以包含方法和计算属性:
enum Suit: String {
    case hearts, diamonds, clubs, spades
    
    var description: String {
        return self.rawValue
    }
}

let suit = Suit.hearts
print(suit.description)  // 输出 "hearts"

以上是一些关于 Swift 枚举的基本用法。Swift 的枚举功能非常强大,可以用于更清晰地表达代码中的概念和数据结构。


转载请注明出处:http://www.zyzy.cn/article/detail/14426/Swift