Swift -- 7.2 枚举
定义枚举类型
与c和oc的枚举不同,swift的枚举成员不会被分配一个默认的整数值。
也就是说,swift的枚举名本身就代表了一个枚举实例,对应一个枚举值,与整数值没有任何关系
enum WeakDay2
{
case Monday
case Tuesday
case Wednesday
case Thursday
case Friday
case Saturday
case Sunday
}
enum WeakDay
{
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
var day : WeakDay
day = WeakDay.Sunday
day = .Wednesday//当程序可以推断出变量的枚举类型时,swift允许省略枚举值前面的枚举名前缀
print(day)
枚举值和switch语句
var chooseDay = WeakDay.Saturday
switch chooseDay
{
case .Monday:
print("monday")
default:
print("non")
}
赋予枚举原始值
如果枚举的类型为Int,赋予原始值的时候程序可以自动推断,类型为String的时候程序不能自动推断,必须给每个枚举指定原始值
enum Season : Character
{
case Spring = "s"
case Summer = "u"
}
var mySeason = Season(rawValue: "s")
if mySeason != nil
{
switch mySeason!
{
case .Spring:
print("spring")
case .Summer:
print("summer")
}
}
构造器
var daya = Season.Spring
print(".Spring的原始值为:\(daya.rawValue)")//获取枚举的原始值
daya = .Summer
print(".Summer的原始值为:\(daya.rawValue)")
var mySeaxon = Season(rawValue: "s")//使用原始值来获取枚举,可能返回nil,这里返回的是可选类型
if mySeason != nil
{
switch(mySeason!){//需要使用!来进行强制解析
case .Spring:
print("s")
case .Summer:
print("u")
}
}
关联值
enum Planet
{
case Mercury(Weight:Double, density:Double, name:String)
case Venus(Double, Double)
case Earth(Double, String)
case Mars(density:Double, name:String)
case Jupiter
case Saturn
case Uranus
case Nepturn
}
var p1 = Planet.Mercury(Weight: 0.05, density: 5.43, name: "水星")
var p2 = Planet.Venus(0.815, 5.25)
var p3 = Planet.Earth(1.0, "地球")
var p4 = Planet.Mars(density: 3.95, name: "水星")
switch(p3)
{
case Planet.Earth(var weight, var name):
print("\(weight)\(name)")
default:
break
}
switch(p1)
{
case let .Venus(weight, density):
print("\(weight)\(density)")
case let .Mercury(Weight:w, density:d, name:n):
print("\(n)")
default:
break
}
枚举这里写了这么多,几乎全都是和switch语句一起用的
根据自己写代码的经验,所以枚举就是用来和switch结合的,来省略繁琐的if判断
所以面向对象的三大特性,封装,继承,多态应该可以实现
面向对象的五大操作方式:
声明变量 可以
创建实例 只能使用定义枚举时定义好的实例什么的,感觉有点别扭
访问类型属性 可以
调用类型方法 可以
派生子类,不是很清楚啊