Swift基础:枚举

136 阅读2分钟

In swift an enum is an object type whose instances represent distinct predefined alternative values. Think of ita as a list of know possibilities. An enum is the Swift way to express a set of constants that are alternatives to on another. An enum declaration includes case statements. Each case is the name of one of the alternatives. An instance of an enum will represent exactly on alternative -- one case. 在swift中enum与Objective-C的风格迥异,定义一个枚举必须要有enum关键字以及枚举名和case标识的枚举条目实例:

enum Swifter {
case zero
case One
case Two
}

创建一个枚举对象:

let s0:Swifter = .zero
var s1:Swifter= .One

枚举的rawValue: 默认情况下枚举的第一个case的rawValue是0,后面case的rawValue会依次增加1即:

enum Swifter {

case zero // 0
case one  // 1
case two  // 2
}

Swift枚举还可以指定其他类型的rawValue:

enum Swifter: String {
  case one = "one"
  case two = "two"
  case three = "three"
}

在Swift中枚举可以拥有associateValue:

enum SharpElement {
case center(x: Double,y: Double)
case size(width: Float, height: Float)
case radius(r: Double)

}

在枚举中添加函数可以访问关联值,使用switch方式进行访问,语法细节在伪代码中展示,请见注释

// 将以下函数添加到枚举类型SharpElement中 伪代码之阐述使用方式
func readValue(se:SharpElement)-> Void {
   switch se {
   case let .center(x: centerX, y: centerY):
   // Access centerX and center Y operation
   case .size(let width, let height):
   // Access width and height operation
   case .radius(let r):
   // Access r operation
   //omit default statement all right
   }
}

Swfit枚举的另一个强大功能就是枚举的迭代表示indirect,伪代码示例:

enum ComputingElement{
case num(Int)
indirect case tuple(element: ComputingElement)
// 伪代码阐述语法使用
static func add(param:ComputingElement) -> Int {
  switch param {
  
  case let .num(x):
  return x
  
  case .tuple(let x, let y):
  return add(param: x) + add(param: y)
  }
 }
}

Swift枚举支持声明泛型,简单举例:

enum GeneralEnum<String, Error> {
case string(String)
case error(Error)
}

枚举的下标方法: 枚举和class以及struct对象一样也可以使用下标方法,并且可以额外遵守协议实现指定枚举值的创建:

enum Season: String, CaseIterable {
   case Spring = "Spring"
   case Summer = "Summer"
   case Autumn = "Autumn"
   case Winter = "Winter"
   
   subscript(index: Int) -> Season? {
      if index > Season.allCase.count - 1 || index < 0 {
      print("越界")
      return nil
      }
      
      return Season.allCase[index]
   }
}

在Swift的enum里也可以定义计算属性、函数以及静态函数,但是不支持存储属性。遵守Caseiterable协议的枚举不用去实现allCase属性直接使用即可。