枚舉是一組相關的值的集合,并允許你在代碼中使用。
枚舉允許所有的值是相同類型的,也可以是不同類型的,還可以為這些值設置默認值。
## 枚舉語法
枚舉使用enum做為關鍵字,后跟枚舉名,其內部值在一個{}內。
空枚舉:
~~~
enum SomeEnumeration {
// enumeration definition goes here
}
~~~
下面這個枚舉包含四個值:
~~~
// 枚舉基本類型
enum CompassPoint {
case North
case South
case East
case West
}
~~~
如果你覺得case的行數太多,枚舉還支持簡寫,將其寫在一行。
~~~
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
~~~
枚舉是一個嶄新的類型,你可以通過let或var去獲得它們。
~~~
// 使用
var directionToHead = CompassPoint.West
~~~
如果你覺得寫枚舉名太麻煩,枚舉還支持不寫枚舉名,直接使用點語法。
~~~
directionToHead = .East
~~~
## 枚舉匹配
你可以使用switch或if做枚舉匹配。
~~~
var directionToHead = CompassPoint.South
// if匹配
if directionToHead == CompassPoint.South {
directionToHead = .East
}
// switch匹配
switch directionToHead {
case .North:
print("Lots of planets have a north")
case .South:
print("Watch out for penguins")
case .East:
print("Where the sun rises")
default:
print("default")
}
~~~
## 關聯值
枚舉支持關聯值,在case后可以使用一個結構體。
~~~
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
~~~
初始化
~~~
var productBarcode = Barcode.UPCA(8, 85909, 51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
~~~
使用switch做匹配,這里用到了let
~~~
switch productBarcode {
case .UPCA(let numberSystem, let manufacturer, let product, let check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
print("QR code: \(productCode).")
}
~~~
如果你覺得let太麻煩了,枚舉的關聯值匹配也支持不寫let。
~~~
switch productBarcode {
case let .UPCA(numberSystem, manufacturer, product, check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .QRCode(productCode):
print("QR code: \(productCode).")
}
~~~
## 原始值
枚舉支持為每個屬性設置原始值,下面設置Character類型的原始值。
~~~
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
~~~
### 隱式分配原始值
在枚舉中,還支持隱式分配枚舉值。
~~~
enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
~~~
在上面的例子中,整個枚舉Planet為Int類型,并設置了Mercury=1。swift會自動為接下來的屬性賦值Venus=2、Earth=3。。。
還有一種情況,你不給任何屬性賦初始值,只是指定了枚舉的類型。Swift也可以自動判斷內部屬性的原始值。
~~~
enum CompassPoint: String {
case North, South, East, West
}
~~~
如上所示,枚舉會使North=”North”、South=“South”、East = “East”和West=“West”。
關于有原始值的枚舉使用如下:
~~~
print("\(Planet.Earth.rawValue)") // 3
print("\(CompassPoint.West.rawValue)") // "West"
~~~
### 通過原始值初始化
如同初始化類,你也可以通過原始值獲取枚舉。
~~~
let possiblePlanet = Planet(rawValue: 7)
~~~
但是通過原始值獲取枚舉時,有的時候獲取不到,會返回nil。
~~~
let positionToFind = 9
// 當原始值不匹配時,返回為nil
if let somePlanet = Planet(rawValue: positionToFind) {
switch somePlanet {
case .Earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
~~~
## 循環枚舉
在枚舉中可以設置任何原始值,同樣可以設置枚舉,并且是當前枚舉,需要用到的關鍵字是indirect。
~~~
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
~~~
如果你覺得每個case都寫indirect太麻煩,枚舉還支持你將indirect寫到enum前。
~~~
indirect enum ArithmeticExpression {
case Number(Int)
case Addition(ArithmeticExpression, ArithmeticExpression)
case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
~~~
下面介紹了怎么運用上面的循環枚舉計算(5 + 4) * 2
~~~
// 函數使用
func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case .Number(let value):
return value
case .Addition(let left, let right):
return evaluate(left) + evaluate(right)
case .Multiplication(let left, let right):
return evaluate(left) * evaluate(right)
}
}
// evaluate (5 + 4) * 2
let five = ArithmeticExpression.Number(5)
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
print(evaluate(product))
~~~
## 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-10-28 | 根據 [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Enumerations總結 |
版權所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結構體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運算符(Advanced Operators)