# 枚举的关联值与原始值

URL: https://caijiao.org/swift/06-enums-structs/02-enum-values
Source: docs/swift/06-enums-structs/02-enum-values.md
Description: 本章讲解 Swift 枚举的关联值与原始值用法，帮助开发者更灵活地使用枚举类型，增强数据表达能力。

Swift 枚举支持关联值和原始值，扩展枚举的功能和表达力。

## 关联值（Associated Values）

关联值允许枚举每个成员携带不同类型的附加数据：

```swift
enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

var productCode = Barcode.upc(8, 85909, 51226, 3)
productCode = .qrCode("ABCDEFGHIJKLMNOP")
````

使用 `switch` 提取关联值：

```swift
switch productCode {
case .upc(let numberSystem, let manufacturer, let product, let check):
    print("UPC: \(numberSystem), \(manufacturer), \(product), \(check)")
case .qrCode(let code):
    print("QR Code: \(code)")
}
```

## 原始值（Raw Values）

原始值是枚举成员固定的默认值，必须类型一致且唯一：

```swift
enum Planet: Int {
    case mercury = 1, venus, earth, mars
}

print(Planet.earth.rawValue)  // 输出 3
```

可以通过原始值初始化枚举：

```swift
if let planet = Planet(rawValue: 2) {
    print(planet)  // 输出 venus
}
```

关联值和原始值使枚举更强大，满足复杂数据场景需求。
