PDF版 ePub版

# 枚举（Enumerations）

## 枚举语法

    enum SomeEnumeration {
// enumeration definition goes here
}

    enum CompassPoint {
case North
case South
case East
case West
}

    enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

    var directionToHead = CompassPoint.West

directionToHead的类型被推断当它被CompassPoint的一个可能值初始化。一旦directionToHead被声明为一个CompassPoint，你可以使用更短的点（.）语法将其设置为另一个CompassPoint的值：

    directionToHead = .East

directionToHead的类型已知时，当设定它的值时，你可以不再写类型名。使用显式类型的枚举值可以让代码具有更好的可读性。

## 匹配枚举值和Switch语句

    directionToHead = .South
case .North:
println("Lots of planets have a north")
case .South:
println("Watch out for penguins")
case .East:
println("Where the sun rises")
case .West:
println("Where the skies are blue")
}
// 输出 "Watch out for penguins”

“考虑directionToHead的值。当它等于.North，打印“Lots of planets have a north”。当它等于.South，打印“Watch out for penguins”。”

    let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
// 输出 "Mostly harmless”

## 相关值（Associated Values）

![Image of Enumerations_1.png]
(images/Enumerations_1.png)

![Image of Enumerations_2.png]
(images/Enumerations_2.png)

    enum Barcode {
case UPCA(Int, Int, Int)
case QRCode(String)
}

“定义一个名为Barcode的枚举类型，它可以是UPCA的一个相关值（IntIntInt），或者QRCode的一个字符串类型（String）相关值。”

    var productBarcode = Barcode.UPCA(8, 85909_51226, 3)

    productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

    switch productBarcode {
case .UPCA(let numberSystem, let identifier, let check):
println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let productCode):
println("QR code with value of \(productCode).")
}
// 输出 "QR code with value of ABCDEFGHIJKLMNOP.”

    switch productBarcode {
case let .UPCA(numberSystem, identifier, check):
println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case let .QRCode(productCode):
println("QR code with value of \(productCode).")
}
// 输出 "QR code with value of ABCDEFGHIJKLMNOP."

## 原始值（Raw Values）

    enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}

    enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

    let earthsOrder = Planet.Earth.rawValue
// earthsOrder is 3

    let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.Uranus

    let positionToFind = 9
if let somePlanet = Planet(rawValue: positionToFind) {
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
} else {
println("There isn't a planet at position \(positionToFind)")
}
// 输出 "There isn't a planet at position 9