1. 枚举定义
enum CompassPoint {
case north
case south
case east
case west
}
或者
enum CompassPoint {
case north,south,east,west
}
//取值
var directionToHead = CompassPoint.west
directionToHead初始化时,推断出的类型CompassPoint。一旦directionToHead被声明为一个CompassPoint,你可以将其设置为不同的CompassPoint使用更短的点语法值:
directionToHead = .east
2. 枚举与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")
}
enum Beverage: CaseIterable {
case coffee, tea, juice
}
let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"
for beverage in Beverage.allCases {
print(beverage)
}
// coffee
// tea
// juice