枚举
//OC 枚举:
enum season {
seasonSpring,
seasonSummer,
seasonAutumn,
seasonWinter
};
enum season thisSeason = seasonSpring;
//: 定义枚举类型,枚举的每个成员前面加case
enum Season {
case Spring
case Summer
case Autumn
case Winter
}
//: 定义一个枚举变量
var season = Season.Spring
//: 再次修改值的时候可以直接 .成员, 是因为类型推导.
season = Season.Summer
season = .Summer
print(season)
Swift判断枚举类型
//: switch判断枚举类型
switch season {
case Season.Spring:
print("春天")
case Season.Summer:
print("夏天")
case Season.Autumn:
print("秋天")
case Season.Winter:
print("冬天")
}
//: 可以省略枚举名
var season2 = Season.Spring
switch season2 {
case .Spring:
print("春天")
case .Summer:
print("夏天")
case .Autumn:
print("秋天")
case .Winter:
print("冬天")
}
枚举成员类型
//: 定义枚举,成员类型为Int
enum Direction: Int {
case North = 0
case South = 1
case East = 2
case West = 3
}
//var direction = Direction.North
//: 使用初始值来定义枚举变量
var direction = Direction(rawValue: 1)
print(direction)
//: 可选绑定
if let dir = direction {
switch dir {
case .North:
print("北")
case .South:
print("南")
case .East:
print("东")
case .West:
print("西")
}
}