枚举(enumerations)
枚举成员可以指定任意类型的关联值存储到枚举成员中,枚举是一等类型。枚举的特性:计算属性,提供枚举值的附加信息,实例方法,提供和枚举值相关联的功能,也可以定义构造函数,来提供一个初始值,可以在原始实现的基础上扩展它们的功能,提供标准功能。
以一个大写字母开头。给枚举类型起一个单数名字而不是复数名字,以便于:var directionToHead = CompassPoint.west
枚举成员的遍历
(1)令枚举遵循 CaseIterable 协议。Swift 会生成一个 allCases 属性,用于表示一个包含枚举所有成员的集合。
enum Beverage: CaseIterable {
case caffee, tea, juice
}
let numberOfChices = Beverage.allCases.count //allCases包含所有枚举成员的集合
print("\(numberOfChices) beverage available") //3 beverage available
(2)使用 for 循环来遍历所有枚举成员
for beverage in Beverage.allCases {
print(beverage)
}
关联值
enum Barcode{
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
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).")
}
//如果一个枚举成员的所有关联值都被提取为常量,或者都被提取为变量,为了简洁,你可以只在成员名称前标注一个 let 或者 var
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
原始值
作为关联值的替代选择,枚举成员可以被默认值(称为原始值)预填充,原始值的类型必须相同。
每个原始值在枚举声明中必须是唯一的,原始值始终不变,关联值可以变化.
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
原始值的隐式赋值
enum Planet : Int {
case mercury, venus, earth, mars, jupiter, saturn, uranus
}
//枚举原始值的隐式赋值
let earthvalue = Planet.earth.rawValue //2
使用原始值初始化枚举实例
//使用了可绑定
let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind){ //创建了一个可选Planet
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
}else{
print("There isn't a planet at position \(positionToFind)")
}
递归枚举(indirect)
递归枚举是一种枚举类型,有一个或多个枚举成员使用该枚举类型的实例作为关联值。使用递归枚举时,编译器会插入一个间接层。可以在枚举成员前加上 indirect 来表示该成员可递归。
//存储简单的算术表达式 递归枚举
enum AirthmeticExpression {
case number (Int)
indirect case addition(AirthmeticExpression, AirthmeticExpression)
indirect case multiplication(AirthmeticExpression)
}
//同上
indirect enum AirthmeticExpression1 {
case number(Int)
case addition(AirthmeticExpression1)
case multiplication(AirthmeticExpression1)
}