Swift学习二
// 定义枚举方式一 enum Season { // 每个case定义一个实例 case Spring case Summer case Fall case Winter } // 定义枚举方式二 enum Weekday { // 使用一个case列出所有枚举实例 case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } // 使用枚举声明变量 var day : Weekday // 使用已有的枚举实例赋值 day = Weekday.Sunday day = .Wednesday // 自动推断为Weekday类型 // 枚举与switch语句一起使用 var chooseDay = Weekday.Saturday switch chooseDay { case .Monday: print("Monday") case .Tuesday: print("Tuesday") case .Friday: print("周五") // 如果没有列举出所有的情况,需要在最后加入一个default来处理其他情况的默认处理 default: print("other day") } // 原始值 /* enum 枚举名 : 原始值类型 { case 枚举值 = 原始值 } */ enum WeekdayHasRawValue: Int { case Monday, Tuesday = 1, wednesday = 5, Sunday } enum SeasonHasRawValue: Character { case Spring = "S" case Summer = "U" case Fall = "F" case Winter = "W" } var aDay = WeekdayHasRawValue.Sunday print(".Sunday的原始值为:\(aDay.rawValue)") var mySeason = SeasonHasRawValue.init(rawValue: "S") // 可能失败的构造器,所以这里要用if let 可选绑定来判断 if let s = mySeason { switch s { case .Spring: print("Spring") default: print("not Spring") } }