Swift 语言之枚举学习笔记

枚举语法

定义:

1
2
3
4
5
6
enum CompassPoint {
case North
case South
case East
case West
}

单行定义:

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

声明:

1
2
var directionToHead = CompassPoint.West
directionToHead = .East

使用switch语句匹配枚举值

1
2
3
4
5
6
7
8
9
10
11
12
directionToHead = .South
switch directionToHead {
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")
}
// prints "Watch out for penguins"

关联值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}

var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
println("QR code: \(productCode).")
}
// prints "QR code: ABCDEFGHIJKLMNOP."

原始值

1
2
3
4
5
6
enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

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

从原始值初始化:

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