swift 枚举

知识点总结:

1、在传递枚举给函数或比较枚举时可以省略枚举类型。

enum TextAlignment{
 case left
 case right
 case center
}

var alignment = TextAlignment.left

alignment = .right
if alignment == .right{

 print("OK")
}

2、原始值枚举:swift支持一系列类型,包括所有内建数值类型和字符串

enum TextAlignment:Int{
 case left = 20
 case right = 30
 case center = 40
}


enum Language:String{
 case swift 
 case objectiveC = "object-c"
 case c
}

如果枚举的原始值为String,并且没有给成员赋值,那么该成员就会默认成员本身的名字一样。

3、获取原始值枚举的值;根据值构造原始值枚举

let alignment = TextAlignment.left.rawValue

let myRawValue = 20
if let myAlignment = TextAlignment(rawValue:myRawValue){
   print("OK")
}

4、枚举的方法

enum Lightbulb{
  case on
  case off
  
  mutating func toggle(){
       switch self {
           case .on:
              self = .off
            case .off:
               self = .on
       }
  }
}

在swift中,枚举是值类型,而值类型的方法不能在方法内对self就行修改,需要添加标记mutating。

5、关联值

enum ShapeDimen{
   case oquare(side:Double)
   case rectangle(width:Double,height:Double)
   case point
}

 

6、递归值

enum FamilyTree{
 case noKnownParents
 indirect case oneKnownParents(name:String,ancestors:FamilyTree)
 indirect case twoKnownParents(fatherName:String,fatherAncestors:FamilyTree,
                           motherName:String,motherAncestors:FamilyTree)
}

swift编译器需要知道程序中每种类型的每个实例占据多少内存空间。尽管一个枚举的实例可能随着程序的运行变为其他成员值,但是编译器知道,同一时间它只会是一个成员值。于是,当编译器判断一个枚举实例需要多少内存的时候,会查看每种成员值并找出需要最多内存的那个。如果一个枚举自己的成员又是自己的话,编辑器就无法知道该枚举的存储空间。swift用关键字indirect告诉编译器把枚举的数据放到一个指针指向的地方。

posted @ 2018-02-08 20:28  燃烧吧,少年  阅读(207)  评论(0编辑  收藏  举报