// 名字的枚举
enum CompassPoint {
case north
case south
case east
case west
}
enum CompassPoint {
case north, south, east, west
}
var directionToHead = CompassPoint.west
directionToHead = .east
switch directionToHead {
case .north:
// ...
case .south:
// ...
case .east:
// ...
case .west:
// ...
}
switch directionToHead {
case .north:
// ...
default:
// ...
}
// 相同类型的枚举
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
enum CompassPoint: String {
case north, south, east, west
}
// CompassPoint.South.rawValue is "South"
enum CompassPoint: Int {
case north = 1, south, east, west
}
// CompassPoint.South.rawValue is 2
let directionToHead = CompassPoint(rawValue: 2)
// directionToHead is of type CompassPoint? and equals CompassPoint.south
let directionToFind = 2
if let directionToHead = Planet(rawValue: directionToFind) {
switch somePlanet {
case .north:
// ...
default:
// ...
}
} else {
// ...
}
// 不同类型的枚举
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):
// ...
case . qrCode(let productCode):
// ...
}
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
// ...
case let .qrCode(productCode):
// ...
}
// 计算周长
enum Shape {
case square(sidelen: Double)
case circle(perimeter: Double)
}
let s = Shape.square(sidelen: 3)
let s2 = Shape.circle(perimeter: 3)
switch(s2) {
case .square(let sidelen): print(sidelen * 4)
case .circle(let perimeter): print(perimeter * 3.14)
}
// 9.42
不同类型值的枚举可以定义自我递归的值。
// 自我递归的枚举
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case .number(let value):
// ...
case .addition(let left, let right):
// ...
case .multiplication(let left, let right):
// ...
}
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
print(evaluate(product))