
列舉 (enumeration) 、類別 (class) 、結構 (structure) 的定義方式都是關鍵字 (keyword) 後加上識別字 (identifier) ,如下圖

列舉是一組常數值的定義,每個常數接在 case 之後被稱為成員 (member) ,基於型態安全 (type-safe) 原則,列舉的成員並不需要設定初值。
通常列舉用在 switch 陳述 (switch statement) 中,藉以判斷執行任務,舉例如下
| enum Numbers { |
| case One |
| case Two |
| case Three |
| case Four |
| } |
| var choice = Numbers.Three |
| switch choice { |
| case .One: |
| println("1") |
| case .Two: |
| println("2") |
| case .Three: |
| println("3") |
| case .Four: |
| println("4") |
| } |
Numbers 為列舉,裡頭定義了四個成員分別是 One 、 Two 、 Three 、 Four ,下面將 choice 設定為 Numbers.Three ,然後用 switch 陳述尋找符合的 case 。
輸入到 Playground ,結果如下

列舉的成員也可以是多個型態 (type) ,這時候就要在成員識別字後加上小括弧,裡頭宣告型態名稱及參數列,例如
| enum Numbers2 { |
| case Five(Int, Int, Int, Int) |
| case Six(String) |
| } |
| let choice2 = Numbers2.Five(1, 2, 3, 4) |
| switch choice2 { |
| case .Five: |
| println("5") |
| case .Six: |
| println("6") |
| } |
輸入到 Playground ,結果如下

當列舉的成員需要設定為特定型態的數值時,這些數值就叫做原始值 (raw value) ,列舉識別字後要加上冒號宣告型態,然後成員直接指派原始值,例如
| enum Numbers3: Int { |
| case Seven = 1 |
| case Eight = 2 |
| case Nine = 3 |
| case Ten = 4 |
| } |
| let decision = 2 |
| if let choice3 = Numbers3(rawValue: decision) { |
| switch choice3 { |
| case .Seven: |
| println("7") |
| case .Eight: |
| println("8") |
| case .Nine: |
| println("9") |
| case .Ten: |
| println("10") |
| } |
| } |
取得 Number3 的成員值要加上參數 rawValue ,而 choice3 的宣告即指派都放在 if 陳述 (if statement) 的條件 (condition) 中,這是因為取出來的列舉成員為選擇型態 (optionals) 。
輸入到 Playground ,結果如下

至於結構與類別在定義上很相似,都是關鍵字 struct 與 class 之後接識別字
| struct StructDemo { |
| // task |
| } |
| class ClassDemo { |
| // task |
| } |
輸入到 Playground ,結果如下

我們在下個單元繼續討論結構與類別兩者的成員,也就是屬性 (property) 及方法 (method) 。
中英文術語對照
| 列舉 | enumeration |
| 類別 | class |
| 結構 | structure |
| 關鍵字 | keyword |
| 識別字 | identifier |
| 成員 | member |
| 型態安全 | type-safe |
| switch 陳述 | switch statement |
| 型態 | type |
| 原始值 | raw value |
| if 陳述 | if statement |
| 條件 | condition |
| 選擇型態 | optionals |
| 屬性 | property |
| 方法 | method |
沒有留言:
張貼留言