原始值和哈希值

没有有效负载的枚举可以具有任何文字类型的原始值

enum Rotation: Int {
    case up = 0
    case left = 90
    case upsideDown = 180
    case right = 270
}

没有任何特定类型的枚举不会公开 rawValue 属性

enum Rotation {
    case up
    case right
    case down
    case left
}

let foo = Rotation.up
foo.rawValue //error

假设整数原始值从 0 开始并单调增加:

enum MetasyntacticVariable: Int {
    case foo  // rawValue is automatically 0
    case bar  // rawValue is automatically 1
    case baz = 7
    case quux  // rawValue is automatically 8
}

字符串原始值可以自动合成:

enum MarsMoon: String {
    case phobos  // rawValue is automatically "phobos"
    case deimos  // rawValue is automatically "deimos"
}

原始值枚举自动符合 RawRepresentable 。你可以使用 .rawValue 获取枚举值的相应原始值:

func rotate(rotation: Rotation) {
    let degrees = rotation.rawValue
    ...
}

你还可以使用 init?(rawValue:) 原始值创建枚举 :

let rotation = Rotation(rawValue: 0)  // returns Rotation.Up
let otherRotation = Rotation(rawValue: 45)  // returns nil (there is no Rotation with rawValue 45)

if let moon = MarsMoon(rawValue: str) {
    print("Mars has a moon named \(str)")
} else {
    print("Mars doesn't have a moon named \(str)")
}

如果你希望获取特定枚举的哈希值,则可以访问其 hashValue,哈希值将返回从零开始的枚举索引。

let quux = MetasyntacticVariable(rawValue: 8)// rawValue is 8
quux?.hashValue //hashValue is 3