Swift枚举

枚举为一组相关的值定义了一个共同的类型,使你可以在你的代码中以类型安全的方式来使用这些值。

如果你熟悉 C 语言,你会知道在 C 语言中,枚举会为一组整型值分配相关联的名称。Swift 中的枚举更加灵活,不必给每一个枚举成员提供一个值。如果给枚举成员提供一个值(称为“原始”值),则该值的类型可以是字符串,字符,或是一个整型值或浮点数。

枚举语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
enum SomeEnumeration {
// 枚举定义放在这里
}

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

enum Planet {
case Mercury, Venus, Earth, Mars
}

var directionToHead = CompassPoint.West
directionToHead = .West

使用switch语句匹配枚举值

1
2
3
4
5
6
7
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
print("Mostly harmless")
default:
print("Not a safe place for humas")
}

关联值

1
2
3
4
5
6
7
8
9
10
11
12
13
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFG")

switch productBarcode {
case .UPCA(let numberSystem, let manufacturer, let product, let check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product) \(check)")
case .QRCode(let productCode):
print("QR code: \(productCode)")
} //输出 "QR code: ABCD"

原始值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}

//原始值的隐式赋值
enum Planet1: Int {
case Mercury = 1, Venus, Earth, Mars
}

enum CompassPoint1: String {
case North, South, East, West
}

let earthsOrder = Planet1.Earth.rawValue // 3
let sunsetDirection = CompassPoint1.West.rawValue //West

//使用原始值初始化枚举实例
let possiblePlant = Planet1(rawValue: 1)!

let positionToFind = 9
if let somePlanet = Planet1(rawValue: positionToFind) {
switch somePlanet {
case .Earth:
print("earth")
default:
print("default")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}

递归枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}

indirect enum ArithmeticExpression1 {
case Number(Int)
case Addition(ArithmeticExpression1, ArithmeticExpression1)
case Multiplication(ArithmeticExpression1, ArithmeticExpression1)
}

let five = ArithmeticExpression.Number(5)
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))

func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case .Number(let value):
return value
case .Addition(let left, let right):
return evaluate(left) + evaluate(right)
case .Multiplication(let left, let right):
return evaluate(left) * evaluate(right)
}
}

print(evaluate(product)) // 输出 "18"

原文链接

–EOF–