Swift
枚举
本文介绍了 Swift 中的枚举(Enumerations),包括基本语法、使用 Switch 匹配、关联值、原始值等。
Swift 的枚举(Enumerations)是一种功能强大的数据类型,它不仅定义了一组相关的值,还支持关联值、原始值、计算属性和实例方法。与 C 或 Objective-C 不同,Swift 的枚举不需要为每个成员分配整数值。
基本语法
使用 enum 关键字定义枚举。
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 = .east使用 Switch 匹配
枚举与 switch 语句配合使用非常自然。Swift 要求 switch 必须穷举所有情况。
directionToHead = .south
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}关联值 (Associated Values)
Swift 枚举可以存储不同类型的关联值。这使得枚举非常适合表达复杂的模型,如结果状态。
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):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}原始值 (Raw Values)
枚举成员可以预填充默认值(原始值),类型必须相同(如 Int, String, Character)。
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}隐式原始值
如果是 Int 或 String,Swift 会自动赋值。
enum Planet: Int {
case mercury = 1, venus, earth, mars // venus=2, earth=3...
}
enum CompassPoint: String {
case north, south, east, west // "north", "south"...
}递归枚举
递归枚举是拥有另一个枚举实例作为关联值的枚举。使用 indirect 关键字。
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))CaseIterable 协议
遵循 CaseIterable 协议可自动生成 allCases 属性,用于遍历所有成员。
enum Beverage: CaseIterable {
case coffee, tea, juice
}
for beverage in Beverage.allCases {
print(beverage)
}在 GitHub 上编辑
上次更新于