Swift-枚举

来源:互联网 发布:修改windows登录界面 编辑:程序博客网 时间:2024/04/30 05:41
 

enum枚举变量类型名:Int {

  case枚举值1 =1

  case枚举值2 =2,枚举值3 =3,枚举值4 =4

  case枚举值5 =5,枚举值6,枚举值7   //如果枚举值是顺序变化的,可以缩写

    

}

 

 

//=================================================================

 

enum IllegalCharacter:Character{

   case Tab    = "\t"

   case Return = "\n"

   case Dot    = "."

   case UnderLine = "_"

}

 

let ilc =IllegalCharacter.UnderLine.rawValue

 

//=================================================================

 

enum Direction {

  case North, South, East, West  //可以不跟类型和行值

}

var direction =Direction.East

direction =Direction.North

direction = .North //Direction可以省略不写

 

//=================================================================

//可以带关联值

//可以带初始化

//可以带算值属性(不能带储值属性)

//可以带方法

 

 

enum TrainStatus {

   case OnTime

  case Delayed(Int)  //关联值:Int

   init(){

      //设置默认值

      self = OnTime

    }

   var desc: String{

      switch self{

          case OnTime:

              return"准时到达"

          case Delayed(let minutes):

              return"延误了\(minutes)分钟"

       }

    }

}

 

//----提取值----

enum Matrix {

   case Xm (Int, Int,Int)    //以元祖作为枚举成员的关联值

   case Ym(String)           //以字符串作为枚举成员的关联值

}

 

var Matrix1 =Matrix.Xm(2,4, 6)

Matrix1 =Matrix.Ym("FIRST")

Matrix1 = .Ym("SECOND")

 

switchMatrix1 {

  case .Xm(let firstInt,let secodeInt,let thirdInt):

      println("Matrix1 =\(firstInt) ,\(secodeInt) ,\(thirdInt)")

   case .Ym(let theString):    //不能写成case Matrix1.Ym

      println("Matrix1 =\(theString)")

}

//如果所有成员都提取出来,则可以简写如下:

switchMatrix1 {

caselet .Xm(firstInt,secodeInt, thirdInt):

  println("Matrix1 =\(firstInt) ,\(secodeInt) ,\(thirdInt)")

casevar .Ym( theString):      //var也可以

  println("Matrix1 =\(theString)")

}

 

//枚举的mutating方法可以把self设置为相同的枚举类型中不同的成员:

enum TriStateSwitch {

   case Off, Low, High

   init(){

      self = Off

    }

   mutating funcnext(){

      switch self{

          case Off:

              self = Low

          case Low:

              self = High

          case High:

              self = Off

       }

    }

}

var switch1 =TriStateSwitch.High

switch1.next()

switch1.hashValue

switch1.next()

switch1.hashValue

 

var switch2 =TriStateSwitch() //有初始化方法才能这样实例化

switch2.hashValue

 


0 0
原创粉丝点击