swift枚举
以下是指南针四个方向的一个例子:
case North
case South
case East
case South
case East
case West
}
多个成员值可以出现在同一行上,用逗号隔开:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
匹配枚举值和 语句 你可以使用 语句匹配单个枚举值:
Compass
directionToHead
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") }
// 输出 "Watch out for penguins”
当不需要匹配每个枚举成员的时候,你可以提供一个默认
let somePlanet = Planet.Earth switch somePlanet {
case .Earth:
print("Mostly harmless") default:
print("Not a safe place for humans") }
// 输出 "Mostly harmless”