Swift中定义Enumeration跟其它语言挺类似的,看如下定义一个星期的Enumeration
enum Day:Int{
case Monday = 1, Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
}
Monday赋值为1其它值则按顺序自动赋值,也是一种比较简便的写法,当然也可以为每个属性赋值
enum Day:Int{
case Monday = 1
case Tuesday = 2,
case Wednesday = 3,Thursday,Friday,Saturday,Sunday
}
let myday = Day.Sunday //自动推测为Day类型的Enumeration
let dayNumber = Day.Sunday.rawValue //值为7
以下定义一个String类型的Enumeration
enum Period:String{
case Morning = "Morning"
case Noon = "Noon"
case AfterNoon = "Afternoon"
case Night = "Night"
case MidNight = "MidNight"
}
Enumeration还有一个很强大的功能叫关值
enum AgeStatus{
case Legal
case NoOldEnought(Int) //关联值
init(){
self = Legal //default value
}
var description:String{
switch self{
case Legal:
return "Age is legal"
case NoOldEnought(let a):
return "Age (a) is illegal"
default:
return "Age is illegal"
}
}
}
var sheAgeStatus = AgeStatus()
sheAgeStatus.description //Age is legal
sheAgeStatus = AgeStatus.NoOldEnought(10)
sheAgeStatus.description // return Age 10 is illegal
Enumeration中还可以定义方法,在上面添加以下方法代码:
func reportStatus() ->String{
return self.description
}
调用方法:
sheAgeStatus.reportStatus()