Support
String / Character / Integer / Float
// 第一个字母大写
enum Planet {
case mercury, venus, earth. mars, jupiter, saturn, uranus, neptune
}
声明与使用
// 不会隐式赋值 0、1、2、3
enum CompassPoint {
case north
case south
case east
case west
}
// 初始化一个 CompassPoint
var directionToHead = CompassPoint.west
// 重新设置不同的 CompassPoint 值,使用 "."
directionToHead = .east
// 匹配 switch
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")
}
获取枚举集合
enum Beverage: CaseIterable {
case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
for bevarage in Beverage.allCases {
print(beverage)
}
原生值 -- 唯一
enum ASCIIControlCharacter: Character {
// 支持 String / Character / Integer / Float
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
隐式分配原生值
enum PlanetInteger: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
// PlantInteger.mercury = 1, PlantInteger.venus = 2
// 字符串原生值默认是 case's name
enum CompassPointString: String {
case north, south, east, west
}
原生值初始化
// 返回可选,因为不是每一个 rawValue 都能对应一个 case
let possiblePlanet = PlanetInteger(rawValue: 7)
let positionToFind = 11
if let somePlanet = PlanetInteger(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
}else {
print("There isn't a planet at position")
}
枚举递归
// 递归 case 前面加 indirect
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// OR
// enum 前面加 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))
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let.addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}